1351. Count Negative Numbers in a Sorted Matrix

LeetCode easy original: C# #array #csharp #easy #leetcode #matrix #sort #string
Il testo del problema è tradotto dal russo per la lingua selezionata. Il codice resta invariato.

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

Esempio:

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# soluzione

abbinato/originale
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++ soluzione

bozza automatica, rivedere prima dell'invio
#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 soluzione

bozza automatica, rivedere prima dell'invio
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 soluzione

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

Go soluzione

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

Algorithm

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

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

Вернуть count.

😎

Vacancies for this task

offerte attive with overlapping task tags are mostrati.

Tutte le offerte
Non ci sono ancora offerte attive.