美文网首页Codility 解决方案 [Swift 3.0]
[Codility] Lession 3.1 TapeEquil

[Codility] Lession 3.1 TapeEquil

作者: sunlitamo | 来源:发表于2016-07-21 22:20 被阅读87次

    Swift Solution:

    public func solution(inout A : [Int]) -> Int {
        guard A.count > 0 else { return 0 }
        
        var leftSum = A[0]
        var rightSum = 0
        
        var diff = [Int]()
    
        for i in 1 ..< A.count { rightSum += A[i] }
    
        for j in 1 ..< A.count {
            let temp = abs(leftSum - rightSum)
            
            leftSum += A[j]
            rightSum -= A[j]
            
            diff.append(temp)
        }
        var result = diff[0]
        for x in 0 ..< diff.count {
            if diff[x] < result {  result = diff[x] }
        }
        return result
    

    相关文章

      网友评论

        本文标题:[Codility] Lession 3.1 TapeEquil

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