{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

1351. Count Negative Numbers in a Sorted Matrix

\n", "
\n", "\n", "\n", "

Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

\n", "\n", "

 

\n", "

Example 1:

\n", "\n", "
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\n",
    "Output: 8\n",
    "Explanation: There are 8 negatives number in the matrix.\n",
    "
\n", "\n", "

Example 2:

\n", "\n", "
Input: grid = [[3,2],[1,0]]\n",
    "Output: 0\n",
    "
\n", "\n", "

Example 3:

\n", "\n", "
Input: grid = [[1,-1],[-1,-1]]\n",
    "Output: 3\n",
    "
\n", "\n", "

Example 4:

\n", "\n", "
Input: grid = [[-1]]\n",
    "Output: 1\n",
    "
\n", "\n", "

 

\n", "

Constraints:

\n", "\n", "\n", "\n", "\n", "

 

\n", "Source \n", "
\n", "\n", "

Code

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def count_negatives(grid):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Check

" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\n", "count_negatives(grid)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grid = [[3,2],[1,0]]\n", "count_negatives(grid)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grid = [[1,-1],[-1,-1]]\n", "count_negatives(grid)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grid = [[-1]]\n", "count_negatives(grid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Follow up:

\n", "

Could you find an O(n + m) solution?

" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "def count_negatives(grid):\n", " pass" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }