สมมติว่าเรามีรายการตัวเลขที่เรียกว่า nums เราต้องการหาความยาวของรายการย่อยที่ติดกัน (contiguous sublist) ที่มีองค์ประกอบทั้งหมดไม่ซ้ำกัน (unique)
ตัวอย่างเช่น หาก nums = [6, 2, 4, 6, 3, 4, 5, 2] ผลลัพธ์จะเป็น 5 เนื่องจากรายการย่อยที่มีองค์ประกอบไม่ซ้ำกันมากที่สุดคือ [6, 3, 4, 5, 2]
ขั้นตอนการแก้ปัญหา (Sliding Window + Hash Map)
- กำหนด
head = 0(จุดเริ่มต้นของหน้าต่าง),dct = {}(เก็บ index ล่าสุดของแต่ละตัวเลข) - กำหนด
max_dist = 0 - วนลูปผ่านแต่ละ
index iและnumในnums:- หาก
numอยู่ในdctและdct[num] >= head:- เลื่อน
head = dct[num] + 1
- เลื่อน
dct[num] = imax_dist = max(max_dist, i - head + 1)
- หาก
- คืนค่า
max_dist
ตัวอย่างโค้ด Python
class Solution:
def solve(self, nums):
head = 0
dct = {}
max_dist = 0
for i, num in enumerate(nums):
if num in dct and dct[num] >= head:
head = dct[num] + 1
dct[num] = i
max_dist = max(max_dist, i - head + 1)
return max_dist
ob = Solution()
nums = [6, 2, 4, 6, 3, 4, 5, 2]
print(ob.solve(nums)) # Output: 5
อินพุต
[6, 2, 4, 6, 3, 4, 5, 2]
เอาต์พุต
5