[LeetCode] 724.Find Pivot Index

This question is the practice of violence is O (N ^ 2), but through observation, we can get a mathematical formula, that is + nums [i] == 2 * current_sum Through this relationship, we can first find out total_sum total_sum, then loop trough, each position i, see if it satisfies this equation. You can meet the return i, remember, every time back loop, current_sum have to put nums [i] current position added to the list.

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        if not nums:
            return -1
        
        total_sum = sum(nums)
        current_sum = 0
        
        for i in range(len(nums)):
            if current_sum == total_sum - current_sum - nums[i]:
                return i
            current_sum += nums[i]
            
            
        return -1

 

Guess you like

Origin www.cnblogs.com/codingEskimo/p/12154600.html