File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ # idea: Hash
2+
3+ class Solution :
4+ def containsDuplicate (self , nums : List [int ]) -> bool :
5+ count_dict = {}
6+ for i in range (len (nums )):
7+ # print(count_dict)
8+ if nums [i ] in count_dict .keys ():
9+ return True
10+ else :
11+ count_dict [nums [i ]] = 1
12+ return False
13+
14+
15+ '''
16+ Trial and error
17+ Printing I/O inside the loop may cause Output Limit Exceeded
18+ '''
Original file line number Diff line number Diff line change 1+ # idea: For each number n in nums, check if (target - n) exists in the remaining elements.
2+
3+ class Solution :
4+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
5+ for idx , num in enumerate (nums ):
6+ required_num = target - num
7+ if required_num in nums [idx + 1 :]:
8+ return [idx , nums .index (required_num , idx + 1 )]
9+
10+
11+ '''
12+ Trial and error
13+ idea : two pointer
14+ I struggled to handle the indices of the original array after sorting it.
15+ The code below fails when negative numbers are involved.
16+ I realized it would be tricky to solve this problem with the two-pointer.
17+ '''
18+
19+ # class Solution:
20+ # def twoSum(self, nums: List[int], target: int) -> List[int]:
21+ # sorted_nums = sorted(nums)
22+ # left, right = 0, len(nums) - 1
23+
24+ # while left < right:
25+ # s = sorted_nums[left] + sorted_nums[right]
26+ # if s == target:
27+ # left_idx = nums.index(sorted_nums[left])
28+ # right_idx = nums.index(sorted_nums[right], left_idx + 1)
29+ # return [left_idx, right_idx]
30+ # elif s < target:
31+ # left += 1
32+ # else:
33+ # right -= 1
34+
You can’t perform that action at this time.
0 commit comments