-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_row_with_max_1s.py
70 lines (54 loc) · 1.71 KB
/
find_row_with_max_1s.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
Given a boolean 2D array of n x m dimensions, consisting of only 1's and 0's, where each row is sorted. Find the 0-based index of the first row that has the maximum number of 1's.
Example 1:
Input:
N = 4 , M = 4
Arr[][] = {{0, 1, 1, 1},
{0, 0, 1, 1},
{1, 1, 1, 1},
{0, 0, 0, 0}}
Output: 2
Explanation: Row 2 contains 4 1's (0-based
indexing).
Example 2:
Input:
N = 2, M = 2
Arr[][] = {{0, 0}, {1, 1}}
Output: 1
Explanation: Row 1 contains 2 1's (0-based
indexing).
Your Task:
You don't need to read input or print anything. Your task is to complete the function rowWithMax1s() which takes the array of booleans arr[][], n and m as input parameters and returns the 0-based index of the first row that has the most number of 1s. If no such row exists, return -1.
Expected Time Complexity: O(N+M)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N, M ≤ 103
0 ≤ Arr[i][j] ≤ 1
"""
#User function Template for python3
class Solution:
def rowWithMax1s(self,arr, n, m):
cnt_max = 0
index = -1
# traverse the rows:
for i in range(n):
# get the number of 1's:
cnt_ones = m - self.lowerBound(arr[i], m, 1)
if cnt_ones > cnt_max:
cnt_max = cnt_ones
index = i
return index
def lowerBound(self, arr, n, x):
low = 0
high = n - 1
ans = n
while low <= high:
mid = (low + high) // 2
# maybe an answer
if arr[mid] >= x:
ans = mid
# look for smaller index on the left
high = mid - 1
else:
low = mid + 1 # look on the right
return ans