题解 | JAVA #矩阵元素查找# [P3]

矩阵元素查找

http://www.nowcoder.com/practice/3afe6fabdb2c46ed98f06cfd9a20f2ce

首先,两点可以确定一个矩形(i.e. 左上+右下)
设左上+右下两点囊括的矩形为M (M初始为整个mat)

不停的去通过比较x与M的右上和左下角的数值的大小,来缩小M的大小。
 x > M右上角, topLeft.row++
 x < M右上角, botRight.col--
 x > M左下角 topLeft.col++
 x < M左下角, botRight.row--

当M缩成一个点时(i.e. 左上==右下),这个点就是答案

举例,以下矩形找5:
1  2  6
4  5  10
7  8  11

loop   左上    右下
初始:[0, 0]  [2, 2]
 1:  [0, 0]  [1, 1]
 2:  [1, 1]  [1, 1]  -> 输出[1, 1] = 5
import java.util.*;

public class Solution {
    public int[] findElement(int[][] mat, int n, int m, int x) {
      int[] topLeft = new int[]{0,0};
      int[] botRight = new int[]{n-1, m-1};
      
      while (topLeft[0] != botRight[0] ||
             topLeft[1] != botRight[1]) {
        if (x > mat[topLeft[0]][botRight[1]])
          topLeft[0]++;
        if (x > mat[botRight[0]][topLeft[1]])
          topLeft[1]++;
          
        if (x < mat[botRight[0]][topLeft[1]])
          botRight[0]--;
        if (x < mat[topLeft[0]][botRight[1]])
          botRight[1]--;
      }
      
      return topLeft;
    }
}
全部评论

相关推荐

05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务