அல்கோரிதம்nested iteration optimization

Nested Iteration Optimization (Avoiding accidental O(n²)) — உட்வளைய மேம்பாடு

TT
Testlaa Team
May 14, 20261 min read

உட்வளையம் — O(n²); hash உள் தேடல்; sort+இரு சுட்டி; மூடிய வடிவம்.

உண்மை உலகில் இது ஏன் முக்கியம்?

மோதல் — இடம் hash. DB join — index seek.

மையக் கருத்து (மாணவர்களுக்கான விளக்கம்)

b எண்ணி dict; a ஒற்றை சுற்று.

Pythonில் முயற்சி செய்வோம்

def count_pairs_sum_to_target(a: list[int], t: int) -> int:
    seen: dict[int, int] = {}
    c = 0
    for x in a:
        c += seen.get(t - x, 0)
        seen[x] = seen.get(x, 0) + 1
    return c


print(count_pairs_sum_to_target([1, 2, 3, 4, 3], 6))

அடிக்கடி நேரும் தவறுகள்

  • வெளி வளையத்தில் sort.
  • inner break — வெளி நிலை.

முக்கியச் சுருக்கக் குறிப்புகள்

  • பெரிய n,m சோதனை.
  • two-sum மாதிரி.

Tags:

Algorithms & complexityPythonமாணவர்கள்