Advertisement
haikid

Untitled

Apr 26th, 2024
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. There is a binary matrix (filled only with 0s and 1s), where every row is sorted. An example:
  2.  
  3. MxN
  4.  
  5. Mxlog(N)
  6.  
  7. 0,1,1,1,1
  8. 0,0,1,1,1
  9. 1,1,1,1,1
  10. 0,0,0,0,0
  11.              
  12. 0,1,1
  13.  
  14. 0 1 2
  15.  
  16. lo = 1
  17. hi = 1
  18.  
  19. mid = 1
  20.  
  21.  
  22. Find the row that contains the most ones.
  23.  
  24. def binarySearch(row):
  25.     lo = 0
  26.     hi = len(row) - 1
  27.    
  28.     while lo <= hi:
  29.         mid = lo + (hi - lo) // 2
  30.         if row[mid] == 0:
  31.             lo = mid + 1
  32.         else: # equals 1
  33.             hi = mid - 1
  34.    
  35.     return lo
  36.    
  37.  
  38. def findRow(matrix):
  39.     N = len(matrix[0])
  40.     rowWithMostOnes = 0
  41.     mostOnesInRow = 0
  42.    
  43.     for index in range(len(matrix)):
  44.         row = matrix[index]
  45.        
  46.         leftMostOne = binarySearch(row)
  47.         currRowOnes = N - leftMostOne
  48.        
  49.         if currRowOnes > mostOnesInRow:
  50.             rowWithMostOnes = index
  51.             mostOnesInRow = currRowOnes
  52.        
  53.     return rowWithMostOnes
  54.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement