码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-02-24 21:25:59      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:tom   find   algorithm   count   tar   slot   nbsp   move   --   

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

标签:tom   find   algorithm   count   tar   slot   nbsp   move   --   

原文地址:https://www.cnblogs.com/Answer1215/p/10427862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!