[724. Find Pivot Index] C++ AC Time & Space: O(n)


  • 0

    Key: Use a vector to store the accumulated sum of vector nums.

    class Solution {
    public:
    int pivotIndex(vector<int>& nums) {
        if(nums.empty()) return -1;
        vector<int> sum(nums.size(),0);
        sum[0] = nums[0];
        for(int i = 1; i < nums.size(); ++i){
            sum[i] = sum[i-1] + nums[i];
        }
        for(int i = 0; i < sum.size(); ++i){
            if(sum[i-1] == (sum.back() - sum[i])) return i;
        }
        return -1;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.