Given an array of integers
We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all 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.
nums
, write a method that returns the "pivot" index of this array.We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all 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
Approach
Java
public class FindPivotIndex {public static void main(String[] args) {int[] nums = { 1, 7, 3, 6, 5, 6 };System.out.println(pivotIndex(nums));}static int pivotIndex(int[] nums) {int n = nums.length;if (n == 0)return -1;int left[] = new int[n];int right[] = new int[n];left[0] = nums[0];right[n - 1] = nums[n - 1];// find the sum of element before position ifor (int i = 1; i < n; i++)left[i] = left[i - 1] + nums[i];// find the sum of element after position ifor (int i = n - 2; i >= 0; i--)right[i] = right[i + 1] + nums[i];for (int i = 0; i < n; i++) {if (left[i] == right[i]) {return i;}}return -1;}}
C++
#include <bits/stdc++.h>using namespace std;int pivotIndex(vector<int> &nums){if (nums.size() == 0)return -1;vector<int> left, right;left.resize(nums.size());right.resize(nums.size());left[0] = nums[0];int n = nums.size();right[n - 1] = nums[n - 1];//find the sum of element before position ifor (int i = 1; i < n; i++)left[i] = left[i - 1] + nums[i];//find the sum of element after position ifor (int i = n - 2; i >= 0; i--)right[i] = right[i + 1] + nums[i];for (int i = 0; i < n; i++){if (left[i] == right[i]){return i;}}return -1;}int main(){vector<int> nums = {1, 7, 3, 6, 5, 6};cout << pivotIndex(nums);return 0;}
No comments:
Post a Comment