LeetCode 888.Fair Candy Swap(公平的糖果棒交换) 哈希表/easy


1.Description

爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。

因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)

返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。

如果有多个答案,你可以返回其中任何一个。保证答案存在。


2.Example

输入:A = [1,1], B = [2,2]
输出:[1,2]

3.Solution

求出A,B两个数组的和,由题意知道当两个数组中的两个值的差是(sumA-sumB)/2时,交换这两个值即可,就得到了答案。使用HashSet比较方便。

    public int[] fairCandySwap(int[] A, int[] B) {
    
    
        Set<Integer> hashSet = new HashSet<Integer>();
    	for(int i=0;i<A.length;i++) {
    
    
        	hashSet.add(A[i]);
        }
    	
    	int suma = 0;
    	int 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[] ans = new int[2];
    	int count = (suma-sumb)/2;
    	for(int i=0;i<B.length;i++) {
    
    
    		if(hashSet.contains(B[i]+count)) {
    
    
    			ans[0] = B[i]+count;
    			ans[1] = B[i];
    		}
    	}
    	return ans;
    }
class Solution {
    
    
    public int[] fairCandySwap(int[] A, int[] B) {
    
    
        int sumA = Arrays.stream(A).sum();
        int sumB = Arrays.stream(B).sum();
        int delta = (sumA - sumB) / 2;
        Set<Integer> rec = new HashSet<Integer>();
        for (int num : A) {
    
    
            rec.add(num);
        }
        int[] ans = new int[2];
        for (int y : B) {
    
    
            int x = y + delta;
            if (rec.contains(x)) {
    
    
                ans[0] = x;
                ans[1] = y;
                break;
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45736160/article/details/114172220