İçeriğe atla
ΣDSA Patterns
Menü
Dil

İki İşaretçi

Rehber 3 / 6 · Yol 3 / 6

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

3Sum Closest

Problem (yeniden ifade)

Bir tamsayı dizisi nums ve tamsayı target verildiğinde, toplamı target’a en yakın olan üç tamsayıyı bul. O toplamı döndür.

Sezgi

Sırala, bir indeksi sabitle, en yakın toplamı izlerken geri kalanı two pointers ile tara. 3Sum ile aynı omurga.

Yaklaşımlar

Sırala + two pointers

Tested only
Time O(n²)Space O(1)

Fikir. Her i için lo/hi taraması; |sum-target| iyileşince en iyiyi güncelle.

Yürüyüş. nums=[-1,2,1,-4], target=1 → en yakın toplam 2.

Trade-off. Sıralamadan sonra O(n²) beklenen; hash’leme en-yakın-toplamı sadeleştirmez.

Solution
export function threeSumClosest(nums: number[], target: number): number {
  nums = [...nums].sort((a, b) => a - b);
  let best = nums[0]! + nums[1]! + nums[2]!;
  for (let i = 0; i < nums.length - 2; i++) {
    let lo = i + 1, hi = nums.length - 1;
    while (lo < hi) {
      const s = nums[i]! + nums[lo]! + nums[hi]!;
      if (Math.abs(s - target) < Math.abs(best - target)) best = s;
      if (s === target) return s;
      if (s < target) lo++; else hi--;
    }
  }
  return best;
}
export function threeSumClosest(nums: number[], target: number): number {
  nums = [...nums].sort((a, b) => a - b);
  let best = nums[0]! + nums[1]! + nums[2]!;
  for (let i = 0; i < nums.length - 2; i++) {
    let lo = i + 1, hi = nums.length - 1;
    while (lo < hi) {
      const s = nums[i]! + nums[lo]! + nums[hi]!;
      if (Math.abs(s - target) < Math.abs(best - target)) best = s;
      if (s === target) return s;
      if (s < target) lo++; else hi--;
    }
  }
  return best;
}

Yansıma