leetcode679
时间: 2024-10-27 14:02:43 浏览: 23
LeetCode 题目 679 可能是指“两数之和 III - 数据结构设计”(Two Sum III - Data Structure Design)。这是一个数据结构题,要求设计一个支持添加、删除元素以及查找两个整数是否存在目标和的数据结构。具体来说,你需要实现一个名为 `TargetSum` 的类:
```python
class TargetSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = [] # 用列表存储所有数字
self.sum_map = {} # 使用哈希表 (字典) 存储每个数字的补数及其索引
def add(self, num: int) -> None:
"""
Adds a new element into the data structure.
:param num: An integer
:return: None
"""
self.nums.append(num)
if num in self.sum_map:
self.sum_map[num].append(len(self.nums)-1)
else:
self.sum_map[num] = [len(self.nums)-1]
def remove(self, val: int) -> None:
"""
Removes a number from the data structure.
:param val: An integer
:return: None
"""
index_to_remove = self.find_index(val)
if index_to_remove is not None:
self.nums.pop(index_to_remove)
for key, indices in self.sum_map.items():
if index_to_remove in indices:
indices.remove(index_to_remove)
def find(self, target: int) -> bool:
"""
Returns if there exists any pair of numbers which sum up to the given target.
:param target: An integer
:return: True if such pair exists, False otherwise.
"""
return self.has_pair(target)
def has_pair(self, target: int) -> bool:
"""
Internal method used by find() to check for a pair using binary search on nums.
"""
left, right = 0, len(self.nums)-1
while left < right:
current_sum = self.nums[left] + self.nums[right]
if current_sum == target:
return True
elif current_sum < target:
left += 1
else:
right -= 1
return False
```
阅读全文