Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def countNegatives(self, grid: List[List[int]]) -> int:
- # Naive
- # Keep track of num neg numbers so far
- num_neg_nums = 0
- # Loop through each row
- for row in grid:
- # If first elem in row is neg, whole row is neg
- if row[0] < 0:
- num_neg_nums += len(row)
- continue
- # If last elem in row is pos, whole row is pos
- if row[-1] >= 0:
- continue
- # Binary search to find lowest positive number in that row
- # Initialise bounds
- left_index = 0
- right_index = len(row) - 1
- # Binary search loop
- while left_index <= right_index:
- # Find mid index and number within bounds
- mid_index = (left_index + right_index) // 2
- mid_num = row[mid_index]
- # If mid num is non-negative and next number is negative
- if mid_num >= 0 and row[mid_index + 1] < 0:
- # Add num neg numbers in row to total
- num_neg_nums += len(row) - (mid_index + 1)
- break
- # If mid num is negative, move to the left
- if mid_num < 0:
- right_index = mid_index - 1
- # If mid num is not negative, move to the right
- else:
- left_index = mid_index + 1
- # Return total num of neg nums
- return num_neg_nums
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement