[LeetCode] 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.

 

Example 2:

Input: 
nums = [1, 2, 3]
Output: -1
Explanation: 
There is no index that satisfies the conditions in the problem statement.

 

Note:

  • The length of nums will be in the range [0, 10000].
  • Each element nums[i] will be an integer in the range [-1000, 1000].

 

這道題給了我們一個數組,讓我們求一個中樞點,使得該位置左右兩邊的子數組之和相等。這道題難度不大,直接按題意去搜索就行了,因為中樞點可能出現的位置就是數組上的位置,所以我們搜索一遍就可以找出來,我們先求出數組的總和,然后維護一個當前數組之和curSum,然后對於遍歷到的位置,用總和減去當前數字,看得到的結果是否是curSum的兩倍,是的話,那么當前位置就是中樞點,返回即可;否則就將當前數字加到curSum中繼續遍歷,遍歷結束后還沒返回,說明沒有中樞點,返回-1即可,參見代碼如下:

 

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        int curSum = 0, n = nums.size();
        for (int i = 0; i < n; ++i) {
            if (sum - nums[i] == 2 * curSum) return i;
            curSum += nums[i];
        }
        return -1;
    }
};

 

類似題目:

Subarray Sum Equals K

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM