888. Fair Candy Swap

作者: 楷书 | 来源:发表于2018-09-16 01:52 被阅读0次

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

Algorithm - array

由于必定有一组解,所以最后的结果一定是两人有同样数量的candy。那么就是求所有candy的和然后对半。之后尝试从A中枚举如果把这个candy給B,那么B是否有对应的candy给A组成一个解。如果可以就返回。

class Solution {
    func fairCandySwap(_ A: [Int], _ B: [Int]) -> [Int] {
        var sum = 0
        
        for a in A {
            sum += a
        }
        
        for b in B {
            sum += b
        }
        
        let halfSum = sum / 2
        
        var existNumber = Set<Int>()
        
        for b in B {
            existNumber.insert(b)
        }
        
        var sumA = 0
        for a in A {
            sumA += a
        }
        
        for a in A {
            let needNumber = halfSum - (sumA - a)
            if existNumber.contains(needNumber) {
                return [a, needNumber]
            }
        }
        
        return [0, 0]
    }
}

相关文章

网友评论

    本文标题:888. Fair Candy Swap

    本文链接:https://www.haomeiwen.com/subject/herxnftx.html