当前位置:网站首页>leetcode每日一题-公平的糖果棒交换
leetcode每日一题-公平的糖果棒交换
2022-06-12 14:51:00 【苏木George】
题目:
爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。
因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)
返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。
如果有多个答案,你可以返回其中任何一个。保证答案存在。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fair-candy-swap
解题思路:
- 1.计算两个原始的数组和之差X,交换的两个数的差需要是X/2即可满足条件。
class Solution {
public int[] fairCandySwap(int[] A, int[] B) {
int[] ans = new int[2];
int sumA = 0, sumB = 0;
for(int i=0;i<A.length;i++){
sumA += A[i];
}
for(int i=0;i<B.length;i++){
sumB += B[i];
}
int cha = sumA-sumB;
for(int i=0;i<A.length;i++){
int numA = A[i];
int numB = numA - cha/2;
for(int j =0;j<B.length;j++)
{
if(numB == B[j]){
ans[0] = numA;
ans[1] = numB;
return ans;
}
}
}
return ans;
}
}
边栏推荐
- USART(RS232422485)、I2C、SPI、CAN、USB总线
- JS (II) syntaxerror: cannot use import statement outside a module
- Scala下载及IDEA安装Scala插件(保姆级教程超详细)
- 能链智电登陆纳斯达克:贝恩是股东 成中国充电服务第一股
- Browser fingerprint interpretation
- Can you believe it? It took me only two days to develop a management system
- Autofac浅学(2)
- Dataset and dataframe in sparksql
- junit测试套件方法整理(方法二不太好用)
- recursive learning
猜你喜欢

Function related matters
![[wp][beginner level] attack and defense world game](/img/07/1ea54d14ba3caca25a68786d5be4a6.png)
[wp][beginner level] attack and defense world game

用游戏来讲序列化与反序列化机制

JMeter (V) pressure test of Excel file upload interface

MAT的安装和使用

Serialization and deserialization mechanism in terms of games

Getting started with webdriver
![[wechat applet] 2 Environmental preparation](/img/8d/7bb68ca7d10751a6e992a53c5eff4a.jpg)
[wechat applet] 2 Environmental preparation

能链智电登陆纳斯达克:贝恩是股东 成中国充电服务第一股

Scala下载及IDEA安装Scala插件(保姆级教程超详细)
随机推荐
Ankai microelectronics rushes to the scientific innovation board: the annual revenue of 500million Xiaomi industry fund is the shareholder
【Calendar】1. For globalization 2 But only date can be formatted by SDF 3 Month to -1 4 Week from Sunday is the first day
Shardingsphere practice (6) - elastic scaling
能链智电登陆纳斯达克:贝恩是股东 成中国充电服务第一股
Structure example
Dataset and dataframe in sparksql
Junit多线程的写法
New technology: efficient self-monitoring visual pre training, local occlusion no longer need to worry!
ADB command (2) use monkey to test
jenkins相关
【Environment】1. Get the configuration in YML through the environment in the configuration class
Leader education was forced to be delisted: Softbank CMC suffered heavy losses only one year after listing
Left aligned, right aligned, random number, goto, compare output bool
Autofac初学(1)
数组相关内容
野指针理解
MySQL index and view
Assertion of selenium webdriver
机器人前行、旋转的service编写
ADB command (I) record