lintcode----统计负数

题目描述:
给一个横向排序的且纵向也排序的的 n * m的矩阵, 问里面有几个负数。

注意事项:
输入的矩阵大小为 n x m ,n <= 500,m <= 500。
为了约束程序的时间复杂度,你的程序将会运行 10^5 次

样例:
Given mat =

[
    [-5,-3,-1,0,1],
    [-2,-1,0,0,1],
    [0,11,12,12,14]
]

return 5.

Explanation:
There are only 5 negative number.

Given mat =

[
    [-50,-30,-10,-5],
    [-30,-20,-5,-1],
    [-10,-5,-1,0]
]

return 11。

Explanation:
There are only 11 negative number.

思路讲解:
首先我们看一下 这个矩阵有两个特殊点,一个是横向有序,另一个是纵向有序。我们如何利用这两个特殊条件进行操作,首先第一个条件,我们可以从后面开始查找,只要找到一个负数,后面就不用继续找了。然后再利用第二个条件,下一次既可以从这个位置开始向前继续寻找(因为列是有序的)。

代码详解:

class Solution {
public:
    /**
     * @param nums: the sorted matrix
     * @return: the number of Negative Number
     */
    int countNumber(vector<vector<int>> &nums) {
        // Write your code here
        int m=nums.size();
        int n=nums[0].size();

        int flag=n-1;//用来存储起始判断点
        int sum=0;//负数和
        for(int i=0;i<m;i++){
            for(int j=flag;j>=0;j--){
                if(nums[i][j]<0){
                    sum=sum+j+1;
                    flag=j;
                    break;
                }
            }
        }
        return sum;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_34355232/article/details/79689548