File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ [Problem]
3+ https://leetcode.com/problems/two-sum/description/
4+
5+ nums.length <= 10^4 => 10,000 * 10,000 => n^2 time complexity일 경우 1초 이상 소요
6+
7+ [Plan]
8+ nums를 hash table로 만들자. (key: element, value: index)
9+ 이후에 nums를 돌면서 target - current_num을 뺀 값이 hash table에 존재한 경우 return하자.
10+ 그랬을 경우, O(n) 시간 복잡도를 예상한다.
11+
12+ [Complexity]
13+ N: nums length
14+ Time: O(N) => HashTable에 nums를 만큼 반복문 돌림
15+ Space: O(N) => nums length 만큼 반복문을 돌면서 hash table을 생성
16+ """
17+
18+ class Solution (object ):
19+ def twoSum (self , nums , target ):
20+ num_to_index_map = dict ()
21+ for index in range (len (nums )):
22+ num_to_index_map [nums [index ]] = index
23+
24+ for index in range (len (nums )):
25+ num = nums [index ]
26+ diff = target - num
27+ # target - num 값이 존재 하지 않을 경우 무시
28+ if not diff in num_to_index_map :
29+ continue
30+ # index가 자기 자신인 경우 무시
31+ if index == num_to_index_map [diff ]:
32+ continue
33+ return [index , num_to_index_map [diff ]]
34+
35+ return [0 , 0 ]
36+
37+
38+ solution = Solution ()
39+ print (solution .twoSum ([3 , 2 , 4 ], 6 ))
You can’t perform that action at this time.
0 commit comments