当前位置:网站首页>Leetcode daily question - fair candy bar exchange

Leetcode daily question - fair candy bar exchange

2022-06-12 15:00:00 George Sumu

subject :

Alice and Bob have candy bars of different sizes :A[i] It's Alice's first i The size of a candy bar ,B[j] It's Bob's first j The size of a candy bar .

Because they are friends , So they want to exchange a candy bar , After this exchange , They all have the same amount of candy .( The total amount of candy a person has is the sum of the size of the candy bars they have .)

Returns an array of integers ans, among ans[0] It's the size of the candy bar Alice has to exchange ,ans[1] yes Bob The size of the candy bars that have to be exchanged .

If there are multiple answers , You can go back to any one of them . Make sure the answer exists .

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/fair-candy-swap

Their thinking :

  • 1. Calculate the difference between the sum of two original arrays X, The difference between the two numbers exchanged needs to be X/2 To meet the conditions .
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;
    }
}
原网站

版权声明
本文为[George Sumu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121451425019.html