Leetcode - subarray-sum-equals-k
Leetcode - find-n-unique-integers-sum-up-to-zero

Leetcode - find-pivot-index

violet posted @ Feb 26, 2020 05:34:36 AM in 算法 with tags array Algorithm Golang 算法 , 285 阅读

https://leetcode.com/problems/find-pivot-index

Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

So the solution is to find a position, that its left sum equals to right sum, something like (0, 1, ..., pivot-1) pivot (pivot+1, ..., size-1). We can sum up all the elements and then do following calculation

sum - currentNum = previousSum * 2
func pivotIndex(nums []int) int {
    if len(nums) == 0 {
        return -1
    }
    if len(nums) == 1{
        return 0
    }
    sum := 0
    for _, n := range nums {
        sum += n
    }
    currentSum := 0
    for i, n := range nums {
        if sum - n == currentSum * 2 {
            return i
        }
        currentSum += n
    }

    return -1
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter