其他分享
首页 > 其他分享> > LeetCode.888 公平的糖果棒交换

LeetCode.888 公平的糖果棒交换

作者:互联网

原题

https://leetcode-cn.com/problems/fair-candy-swap/

在这里插入图片描述
思路
哈希表,推导等式 sumA - x + y = sumB + x - y

解题

package com.leetcode.code;

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

/**
 * @ClassName Code888
 * @Author ZK
 * @Description
 * @Date 2021/2/1 17:02
 * @Version 1.0
 **/
public class Code888 {

    public static void main(String[] args) {

    }

    /**
     * 暴力
     * @param A
     * @param B
     * @return
     */
    public static int[] fairCandySwap0(int[] A, int[] B) {
        int[] res = new int[2];
        int sumA = Arrays.stream(A).sum();
        int sumB = Arrays.stream(B).sum();
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B.length; j++) {
                if (sumA - A[i] + B[j] == sumB + A[i] - B[j]) {
                    res[0] = A[i];
                    res[1] = B[j];
                }
            }
        }
        return res;
    }

    /**
     * hash表
     * @param A
     * @param B
     * @return
     */
    public static int[] fairCandySwap(int[] A, int[] B) {
        int[] res = new int[2];
        int sumA = Arrays.stream(A).sum();
        int sumB = 0;
        Set<Integer> set = new HashSet<>();
        for (int x : B) {
            set.add(x);
            sumB += x;
        }

        for (int x : A) {
            int temp = x - (sumA - sumB)/2;
            if (set.contains(temp)) {
                res[0] = x;
                res[1] = temp;
            }
        }
        return res;
    }

}

标签:int,res,param,public,公平,糖果,sumB,sumA,LeetCode.888
来源: https://blog.csdn.net/wazk2008/article/details/113530545