File tree Expand file tree Collapse file tree 3 files changed +51
-13
lines changed Expand file tree Collapse file tree 3 files changed +51
-13
lines changed Original file line number Diff line number Diff line change 5
5
# The size of the set for storing deduplicated elements is proportional to the length of the input list.
6
6
7
7
class Solution :
8
- def containsDuplicate (self , nums : list [ int ]) -> bool :
9
- list_len = len (nums )
10
- set_len = len (set (nums ))
8
+ def containsDuplicate (self , nums ) :
9
+ list_num = len (nums )
10
+ set_num = len (set (nums ))
11
11
12
- return list_len != set_len
12
+ if list_num != set_num :
13
+ return True
14
+ else :
15
+ return False
13
16
14
17
if __name__ == "__main__" :
15
18
solution = Solution ()
Original file line number Diff line number Diff line change 8
8
# - and when sorting takes O(n), hash[x] occupy O(1)
9
9
10
10
class Solution :
11
- def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
12
- hash = dict ()
11
+ def topKFrequent (self , nums , k ):
12
+ """
13
+ :type nums: List[int]
14
+ :type k: int
15
+ :rtype: List[int]
16
+ """
13
17
14
- # for loop nums to set count for each element in hash(dictionary)
15
- for num in nums :
16
- if num in hash :
17
- hash [num ] += 1
18
+ dic = {}
19
+
20
+ for v in nums :
21
+ if v in dic :
22
+ cur = dic [v ]
23
+ cur += 1
24
+ dic [v ] = cur
18
25
else :
19
- hash [num ] = 1
26
+ dic [v ] = 1
27
+
28
+ reverse_desc = sorted (dic .items (), key = lambda item : item [1 ], reverse = True )
20
29
21
- # sort (TimSort), using lambda function to set a sorting key which is a count
22
- return sorted (hash , key = lambda x : hash [x ], reverse = True )[:k ]
30
+ n = 0
31
+ result = []
32
+ for v in reverse_desc :
33
+ if n == k :
34
+ break
35
+
36
+ result .append (v [0 ])
37
+ n += 1
38
+
39
+ return result
23
40
24
41
if __name__ == "__main__" :
25
42
solution = Solution ()
Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def twoSum (self , nums , target ):
3
+
4
+ """
5
+ :type nums: List[int]
6
+ :type target: int
7
+ :rtype: List[int]
8
+ """
9
+
10
+ dic = {}
11
+
12
+ for i , v in enumerate (nums ):
13
+ complement = target - v
14
+
15
+ if complement in dic :
16
+ return [i , dic [complement ]]
17
+
18
+ dic [v ] = i
You can’t perform that action at this time.
0 commit comments