faster implementation of sum ( for Codility test )

前端 未结 22 2099
鱼传尺愫
鱼传尺愫 2021-02-04 11:47

How can the following simple implementation of sum be faster?

private long sum( int [] a, int begin, int end ) {
    if( a == null   ) {
        ret         


        
22条回答
  •  悲&欢浪女
    2021-02-04 12:22

    This may be old, but here is solution in Golang with 100% pass rate:

    package solution
    
    func Solution(A []int) int {
        // write your code in Go 1.4
        var left int64
        var right int64
        var equi int
    
        equi = -1
        if len(A) == 0 {
            return equi
        }
    
        left = 0
        for _, el := range A {
            right += int64(el)
        }
    
        for i, el := range A {
            right -= int64(el)
            if left == right {
                equi = i
            }
            left += int64(el)
        }
    
        return equi
    }
    

提交回复
热议问题