JSFiddle - React, Tailwind, and code Playground
by Slava Slava
JavaScript
const nums2 = [1, 2, 3] // -1
const num3 = [2, 1, -1] // 0
const nums4 = [2, 3, -1, 8, 4] // Output: 3
const nums = [1, 7, 3, 6, 5, 6] // 3
var pivotIndex = function(nums) {
const total = nums.reduce((acc, i) => acc += i, 0);
let leftSum = 0;
for (let i = 0; i < nums.length; i++) {
const current = nums[i];
if (leftSum === total - leftSum - current) {
return i
}
leftSum += current
/* if left_sum == total_sum - left_sum - nums[i]:
return i
left_sum += nums[i] */
}
return -1
}
console.log(pivotIndex(nums)) // it should be 3, not -1
// ---------------------------------
/* var pivotIndex = function(nums) {
let start = 0
let end = 0
const middle = Math.round(nums.length / 2)
console.log(middle)
for (let i = 0; i <= nums.length - 1; i++) {
let left = nums[i]
let right = nums[nums.length - 1 - i]
const stepsLeft = middle - i
console.log('sss', stepsLeft)
// console.log('left', left)
// console.log('right', right)
if (start === end) {
}
console.log('-------------')
}
console.log(left, right)
};
const nums = [1, 7, 3, 6, 5, 6] // 3
const nums2 = [1, 2, 3] // -1
const num3 = [2, 1, -1] // 0
const nums4 = [2,3,-1,8,4] // Output: 3
console.log(pivotIndex(nums)) */