Easyprefix-sum
Find Pivot Index
Problem (yeniden ifade)
Sol elemanların toplamının sağ elemanların toplamına eşit olduğu en soldaki pivot indeksini döndür; yoksa -1.
Sezgi
Toplam sabit; yürüdükçe leftSum büyür ve rightSum = total, leftSum, nums[i].
Yaklaşımlar
Koşan sol toplam
Tested onlyTime O(n)Space O(1)
Fikir. total hesapla. Her i için leftSum == total, leftSum, nums[i] ise i döndür. Değilse leftSum += nums[i].
Adım adım. [1,7,3,6,5,6] → pivot indeks 3 (1+7+3 = 5+6).
Trade-off’lar. Önek dizileri O(n) alan kullanır; koşan toplam yeter.
Solution
export function pivotIndex(nums: number[]): number {
const total = nums.reduce((a, b) => a + b, 0);
let left = 0;
for (let i = 0; i < nums.length; i++) {
if (left === total - left - nums[i]!) return i;
left += nums[i]!;
}
return -1;
}
export function pivotIndex(nums: number[]): number {
const total = nums.reduce((a, b) => a + b, 0);
let left = 0;
for (let i = 0; i < nums.length; i++) {
if (left === total - left - nums[i]!) return i;
left += nums[i]!;
}
return -1;
}
Yansıma
- 90 saniyenin altında hangi ipucu bu kalıbı seçtirdi?
- Hangi girdi yanlış bir değişmezi bozar?