classSolution { public: intpivotIndex(vector<int> &nums){ int total = accumulate(nums.begin(), nums.end(), 0); int sum = 0; for (int i = 0; i < nums.size(); ++i) { if (2 * sum + nums[i] == total) { return i; } sum += nums[i]; } return-1; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicintpivotIndex(int[] nums) { inttotal= Arrays.stream(nums).sum(); intsum=0; for (inti=0; i < nums.length; ++i) { if (2 * sum + nums[i] == total) { return i; } sum += nums[i]; } return -1; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution { publicintPivotIndex(int[] nums) { int total = nums.Sum(); int sum = 0; for (int i = 0; i < nums.Length; ++i) { if (2 * sum + nums[i] == total) { return i; } sum += nums[i]; } return-1; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcpivotIndex(nums []int)int { total := 0 for _, v := range nums { total += v } sum := 0 for i, v := range nums { if2*sum+v == total { return i } sum += v } return-1 }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var pivotIndex = function(nums) { const total = nums.reduce((a, b) => a + b, 0); let sum = 0; for (let i = 0; i < nums.length; i++) { if (2 * sum + nums[i] === total) { return i; } sum += nums[i]; } return -1; };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
intpivotIndex(int* nums, int numsSize) { int total = 0; for (int i = 0; i < numsSize; ++i) { total += nums[i]; } int sum = 0; for (int i = 0; i < numsSize; ++i) { if (2 * sum + nums[i] == total) { return i; } sum += nums[i]; } return-1; }