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.

原题链接:https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1144/

 就是找到一个索引,使之左侧所有元素相加的和等于右侧所有元素相加的和

先求出前缀和,index处的左侧元素等于相加和为index - 1 处的前缀和,右侧元素相加和为所有元素之和与 index 车的 前缀和之差。

c++代码

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
int pivotIndex(vector<int>& nums) {
    int sum = 0;
    vector<int> presum;
    presum.push_back(sum);
    for (int i = 0; i < nums.size(); i++) {
        sum += nums[i];
        presum.push_back(sum);
    }

    int size = presum.size();

    for (int i = 1; i < size; i++) {
        if (presum[i - 1] == presum[size - 1] - presum[i]) {
            return i - 1;
        }
    }
    return -1;
}

};

int main() {
    int arr[] = {-1,-1,0,1,1,0};
    vector<int> vec1(arr, arr + 6);

    cout << Solution().pivotIndex(vec1) << endl;

    return 0;
}

Java代码

class Solution {
	public int pivotIndex(int[] nums) {

		int[] sum = new int[nums.length + 1];
		sum[0] = 0;
		for (int i = 0; i < nums.length; i++)
			sum[i+1] = sum[i] + nums[i];

		for (int i = 1; i < sum.length; i++) {
			int left = sum[i - 1];
			int right = sum[sum.length - 1] - sum[i];
			if (left == right)
				return i - 1;
		}

		return  -1;
	}

	public static void main(String[] args) {
		Solution res = new Solution();
		int[] arr = {-1,-1,0,1,1,0};
		System.out.println(res.pivotIndex(arr));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值