问题描述
例如,我有数组 p=[5,3,9,8]
,元素 9 有索引 x=2
,并且该索引分为两个分区,并且这两个分区的总和必须相同。
(或者他们不必分区,我不知道......)
第一个分区是 5,3
,第二个是 8
。
sum([5,3]) = 8
sum([8]) = 8
更多示例...
p=[3,2,1,3]
output: x=3
p=[3,17,1]
output: x=1
来自用户输入界面的随机数。如何在javascript代码中编写以获取索引x的输出,它与两个相等的和分开?
解决方法
用两个指针在O(n)时间和常数空间内求解如下:
const findTheIndex = (arr = []) => {
if (!arr || arr.length < 3) {
return -1
}
let left = 0
let right = arr.length - 1
let leftSum = arr[0]
let rightSum = arr[right]
left += 1
right -= 1
while (left < right) {
if (leftSum < rightSum) {
leftSum += arr[left]
left += 1
} else {
rightSum += arr[right]
right -= 1
}
}
if (leftSum == rightSum) {
return left;
}
return -1
};
console.log(findTheIndex([2,3,8,5]))
console.log(findTheIndex([3,2,1,3]))
console.log(findTheIndex([3,17,1]))
console.log(findTheIndex([1,4]))