首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。