首页 > 代码库 > Pivot Index--Google

Pivot Index--Google

Return the pivot index of the given array of numbers. The pivot index is the index where the sum of the numbers on the left is equal to the sum of the numbers on the right. Input Array {1,2,3,4,0,6} 
return 3
 
One for loop to calculate sum, then another loop to compare (sum-nums[j]-leftsum)==leftsum?
if true return j, if false, then update leftsum=sum-nums[j]
 
 1 public int PivotIndex(int[] nums)
 2         {
 3             if (nums == null || nums.Length == 0)
 4             {
 5                 return -1;
 6             }
 7             int l = nums.Length;
 8             int sum = 0; int leftsum = 0;
 9             for (int i = 0; i < l; i++)
10             {
11                 sum +=nums[i];
12             }
13             for (int j=0; j< l; j++)
14             {
15                 if (sum - nums[j] - leftsum == leftsum)
16                 {
17                     return j;
18                 }
19                 else
20                     leftsum += nums[j];
21             }
22             return -1;
23         }

 

Pivot Index--Google