最左侧的1

类似如下grid:每个横⾏行行只要出现1,右边的数字都会是1。例例⼦子中的最左侧的1是倒数第⼆二⾏行行第⼆二列列的那 个。
000011
001111 
000001
 001111 
011111
 000111 







public int[] leftMostOne(int[][] grid){
  
  // col 
  firCol = getLeft(grid[0]);
  firRow = 0;
  for(int i = 1 ; i < grid.length; i++){
    // check if better or the same , if better or the same
    // do the binary search , else continue;
    if(better(grid[i], firCol){
      int nextCol = getLeft(grid[i]);
      // update if nextRow left MOST ONE  < firstRow left most one 
      if(firCol > nextCol){
        firCol = nextCol;
        firRow = i;
      }
    }else{
      continue;
    }
  }
  return new int[]{firRow, firCol};
}

private int getLeft(int[] input){
  // binary search 
  int left = 0;
  int right = input.length;
  
  while(left < right){
    int mid = left + (right - mid) / 2;
    if(input[mid] == 0){
      left = mid + 1;
    }else{
      right = mid;
    }
  }
  return left;
}

private boolean better(int[] input, int lastRes){
  
  if(input[lastRes] == 1){
    return true;
  }else{
    return false;
  }
}

 

posted on 2018-08-28 20:12  猪猪&#128055;  阅读(133)  评论(0)    收藏  举报

导航