File tree 2 files changed +59
-0
lines changed
2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Link: https://leetcode.com/problems/reduce-array-size-to-the-half/
2
+
3
+ import heapq
4
+
5
+ def minSetSize (arr ):
6
+ half_len = len (arr )// 2
7
+ # Hash table to keep track of the number of occurrences
8
+ num_count = {}
9
+
10
+ for num in arr :
11
+ if num in num_count :
12
+ num_count [num ] += 1
13
+ else :
14
+ num_count [num ] = 1
15
+
16
+ # Initialize an empty max heap sorted by decreasing order of
17
+ # occurences. Make the count negative to achieve this effect
18
+ # since heapq only provides implementation for a min heap
19
+ max_heap = []
20
+ for num , count in num_count .items ():
21
+ curr_pair = [- count , num ]
22
+ heapq .heappush (max_heap , curr_pair )
23
+
24
+ # The number of integers that we removed so far
25
+ num_removed = 0
26
+ num_elements = 0
27
+ while num_removed < half_len and len (max_heap ) > 0 :
28
+ # Current number with the greatest number of occurrences
29
+ curr_max = heapq .heappop (max_heap )
30
+ # Turn the count back to positive value and add them
31
+ num_removed += - (curr_max [0 ])
32
+ num_elements += 1
33
+
34
+ return num_elements
Original file line number Diff line number Diff line change
1
+ def plusOne (digits ):
2
+ num_digits = len (digits )
3
+ ans = [0 ]* num_digits
4
+ i = num_digits - 1
5
+
6
+ while i >= 0 :
7
+ curr_digit = digits [i ]
8
+ if curr_digit < 9 :
9
+ ans [i ] = curr_digit + 1
10
+ break
11
+ else : # curr_digit == 9
12
+ # "Carry the 1"
13
+ ans [i ] = 0
14
+ i -= 1
15
+
16
+ # EDGE CASE: All of the digits are 9s
17
+ if i < 0 :
18
+ return [1 ] + ans
19
+
20
+ # If necessary, populate the rest of the numbers
21
+ while i > 0 :
22
+ i -= 1
23
+ ans [i ] = digits [i ]
24
+
25
+ return ans
You can’t perform that action at this time.
0 commit comments