[Algorithm] Count Negative Integers in Row/Column-Wise Sorted Matrix

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algorithm] Count Negative Integers in Row/Column-Wise Sorted Matrix相关的知识,希望对你有一定的参考价值。

Each row and each column are already SORTED in the given matrix! 

 

const mix = [[-3, -2, -1, 3], [-1, 0, 1, 3], [0, 2, 4, 5]];

/**
 * Start from top right slot, go from right to left, top to bottom
 * case 1; If the current value is larger than 0, keep moving to left
 * case 2: if the current value is smaller than , menas the rest of value should
 *  also less than zero, count = count + 1 + j
 *  then move to next row
 */
// findNegativeNumbers :: [num] -> num
function findNegativeNumbers(data) {
  let count = 0;
  let i = 0,
    j = data[0].length - 1;
  while (i <= data.length - 1 && j >= 0) {
    const current = data[i][j];
    if (current >= 0) {
      j--;
    } else {
      count += j + 1;
      i++;
    }
  }
  return count;
}

console.log(findNegativeNumbers(mix)); // 4

 

以上是关于[Algorithm] Count Negative Integers in Row/Column-Wise Sorted Matrix的主要内容,如果未能解决你的问题,请参考以下文章

STL algorithm算法详解

3 - Two Pointers Algorithm

BZOJ 1452 Count

Bzoj1452 Count

[bzoj] 1036 Count

poj2777 Count Color