본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1351. Count Negative Numbers in a Sorted Matrix

반응형

https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. grid의 행 r, 열 c를 선언 후 값을 저장합니다.2. 정답변수 negatives를 선언 후 0으로 초기화해줍니다.

📔 풀이과정

grid의 원소를 순회하며 음수의 개수를 세줍니다.

📔 정답 출력 | 반환

negatives를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int countNegatives(vector<vector<int>>& grid) {
        int r = grid.size();
        int c = grid[0].size();
        int negatives = 0;
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                if(grid[i][j] < 0) negatives++;
            }
        }
        return negatives;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.