Tuesday, March 16, 2021

Leetcode Everyday: 1351. Count Negative Numbers in a Sorted Matrix. Easy

public int CountNegatives(int[][] grid) {
    var count = 0;
    foreach (var line in grid) {
        for (var i = 0; i < line.Length; ++i) {
            if (line[i] <0) {
                count += line.Length - i;
                break;
            }
        }
    }
    return count;
}

// TODO: Create a binary search approach
Functional:
public class Solution {
	public int CountNegatives(int[][] grid) => grid.SelectMany(line => line).Count(n => n < 0);    
}
Source: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/

No comments:

Post a Comment