← Static tasks

1351. Count Negative Numbers in a Sorted Matrix

leetcode easy

#array#csharp#easy#leetcode#matrix#sort#string

Task

Дана матрица m x n grid, которая отсортирована по убыванию как по строкам, так и по столбцам. Вернуть количество отрицательных чисел в grid.

Пример:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]

Output: 8

Explanation: There are 8 negatives number in the matrix.

C# solution

matched/original
public class Solution {
    public int CountNegatives(int[][] grid) {
        int count = 0;
        foreach (var row in grid) {
            foreach (var element in row) {
                if (element < 0) {
                    count++;
                }
            }
        }
        return count;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int CountNegatives(int[][] grid) {
        int count = 0;
        foreach (var row in grid) {
            foreach (var element in row) {
                if (element < 0) {
                    count++;
                }
            }
        }
        return count;
    }
}

Java solution

auto-draft, review before submit
import java.util.*;
import java.math.*;

// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
    public int CountNegatives(int[][] grid) {
        int count = 0;
        foreach (var row in grid) {
            foreach (var element in row) {
                if (element < 0) {
                    count++;
                }
            }
        }
        return count;
    }
}

Python solution

matched/original
class Solution:
    def countNegatives(self, grid):
        count = 0
        for row in grid:
            for element in row:
                if element < 0:
                    count += 1
        return count

Go solution

matched/original
func countNegatives(grid [][]int) int {
    count := 0
    for _, row := range grid {
        for _, element := range row {
            if element < 0 {
                count++
            }
        }
    }
    return count
}

Explanation

Algorithm

Инициализировать переменную count = 0 для подсчета общего числа отрицательных элементов в матрице.

Использовать два вложенных цикла для итерации по каждому элементу матрицы grid, и если элемент отрицательный, увеличить count на 1.

Вернуть count.

😎