0
点赞
收藏
分享

微信扫一扫

《中英双解》leetcode Fair Candy Swap(公平糖果的交换)

十里一走马 2022-02-18 阅读 31
package Sort;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class FairCandySwap {
    public static int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
//        int[] answer = new int[2];
//        int i = 0;
//        int j = 0;
//        int resultAlice = 0;
//        int resultBob = 0;
//        for(int k = 0;k < aliceSizes.length;k++){
//            resultAlice += aliceSizes[k];
//        }
//        for(int k = 0;k < bobSizes.length;k++){
//            resultBob += bobSizes[k];
//        }
//        for(;i < aliceSizes.length;i++){
//            for(;j < bobSizes.length;j++){
//                //存储i,j此时的元素
//                answer[0] = aliceSizes[i];
//                answer[1] = bobSizes[j];
//                if((resultAlice - answer[0] + answer[1]) == (resultBob - answer[1]  + answer[0])){
//                    break;
//                    //return answer;
//                }
//            }
//            if((resultAlice - answer[0] + answer[1]) == (resultBob - answer[1]  + answer[0])){
//                break;
//                //return answer;
//            }
//            if(j == bobSizes.length){
//                j = 0;
//            }
//        }
//        return answer;
        int sumA = Arrays.stream(aliceSizes).sum();
        int sumB = Arrays.stream(bobSizes).sum();
        int delta = (sumA - sumB) / 2;
        Set<Integer> rec = new HashSet<Integer>();
        for (int num : aliceSizes) {
            rec.add(num);
        }
        int[] ans = new int[2];
        for (int y : bobSizes) {
            int x = y + delta;
            if (rec.contains(x)) {
                ans[0] = x;
                ans[1] = y;
                break;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] answer = new int[2];
        int[] aliceSize = new int[]{35,17,4,24,10};
        int[] bobSize = new int[]{63,21};
        answer = fairCandySwap(aliceSize,bobSize);
        for(int i = 0;i < answer.length;i++){
            System.out.println(answer[i]);
        }
    }
}

 

举报

相关推荐

0 条评论