[数组]724. Find Pivot Index

2018-03-06  本文已影响0人  Reflection_

724. Find Pivot Index
时间复杂度为o(n),空间复杂度为o(1).

方法一:Java

class Solution {
    public int pivotIndex(int[] nums) {
        if(nums.length == 0) return -1;
        //第一次遍历,sum all
        int sum = 0;
        for(int i = 0; i< nums.length ;i++){
            sum+= nums[i];
        }
        
//         第二次遍历,当 2*(前sum + this )== sum all时,返回this
        int subsum = 0;
        for(int j = 0; j < nums.length; j++){
            if(subsum*2 + nums[j] == sum)return j;
            else subsum += nums[j];
        }
        
        return -1;
    }
}

方法二:Python

class Solution(object):
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
#        遍历第一次 计算每个到当前i的subsum
        subsum =[]
        s = 0
        for i in nums:
            s += i
            subsum.append(s)
#         遍历第二次 当左subsum == 总sum-当前subsum(右subsum)
        for ind in range(1,len(nums)):
            if(subsum[ind-1] == subsum[len(nums)-1] - subsum[ind]):
                return ind
        
        return -1
            
    
上一篇下一篇

猜你喜欢

热点阅读