[LeetCode] 724. Find Pivot Index

Description

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

Analyse

给定一个数组nums,找到一个index,使得 sum[0, index) == sum(index, nums.size()-1]

暴力解法,很简单,性能也意料之中的差

对于每个index都算一遍 sum[0, index)sum(index, nums.size()-1]

int sumRange(vector<int>& nums, int left, int right)
{
    int sum = 0;
    for (int i = left; i < right; i++)
    {
        sum += nums[i];
    }
    return sum;
}

int pivotIndex(vector<int>& nums)
{
    int sum_left = 0;
    int sum_right = 0;

    for (int i = 0; i < nums.size(); i++)
    {
        sum_left = sumRange(nums, 0, i);
        sum_right = sumRange(nums, i+1, nums.size());

        if (sum_left == sum_right)
        {
            return i;
        }
    }

    return -1;
}

改进一下,将计算结果保存下来以减少计算次数

先计算一个sum数组

sum[i] 代表下标i左边元素之和(不包括 nums[i]

sum[i] = nums[0] + nums[1] + ... + nums[i-1]

下标i右边元素的和为 sum[nums.size()-1] - sum[i+1]

对于每个下标i,比较sum[i] 和 sum[nums.size()-1] - sum[i+1]是否相等即可

index 0  1  2   3   4  5
nums [1, 7, 3,  6,  5, 6]
sum  [0, 1, 8, 11, 17, 22, 28]
int pivotIndex(vector<int>& nums)
{
    if (nums.size() == 0) return -1;
    int sum_left = 0;
    int sum_right = 0;

    vector<int> sum;
    sum.push_back(0);
    sum.push_back(nums[0]);

    for (int i = 1; i < nums.size(); i++)
    {
        sum.push_back(sum[i] + nums[i]);
    }

    for (int i = 0; i < nums.size(); i++)
    {
        sum_left = sum[i];
        sum_right = sum[nums.size()] - sum[i+1];
        if (sum_left == sum_right)
        {
            return i;
        }
    }

    return -1;
}

下面的解法来自LeetCode,与上面的解法思路类似,但并不算出完整的sum数组,只计算nums的和,

使用一个left_sum保存下标i左边元素之和,
下标i右边元素之和由sum保存

每一次循环都更新left_sumsum

int pivotIndex(vector<int>& nums)
{
    int size = nums.size();
    int left_sum = 0;

    auto sum = std::accumulate(cbegin(nums), cend(nums), 0);

    for (int i = 0; i < size; i++)
    {
        sum -= nums[i];
        if (left_sum == sum) {
            return i;
        }

        left_sum += nums[i];
    }

    return -1;
}
posted @ 2019-11-01 14:25  arcsinW  阅读(150)  评论(0编辑  收藏  举报