剑指offer(题三)
来源:互联网 发布:凯驰吸尘器 知乎 编辑:程序博客网 时间:2024/05/21 14:54
题意:给出一个二维矩阵,每行、每列都递增排序。查找这个矩阵中的某个数,看是否存在。
思路:每次看最右上角的数,若和待查找的数相等,则返回;若是大于目标数,则将矩阵中的该列删除;若是小于目标数,则将矩阵中的该行删除。同样,也可每次看最左下角的数字。
代码:
package MianShiTi_3;public class MianShiTi_3 { //从最右上角开始查找 public boolean Find(int [][]matrix ,int target){ int rows = matrix.length; int columns = matrix[0].length; boolean find = false; if(matrix != null && rows > 0 && columns > 0){ int row = 0; int column = columns -1; while (row < rows && column >=0) { if(matrix[row][column] == target){ find = true; break; }else if (matrix[row][column] > target) { column -- ; }else { row++; } } } return find; } //从最左下角开始查找 public String Find2(int [][]matrix ,int target){ int rows = matrix.length; int columns = matrix[0].length; String s1 = "bingo"; String s2 = "foolish"; if(matrix != null && rows > 0 && columns >0){ int row = rows - 1; int column = 0; while (column < columns && row >=0) { if(matrix[row][column] == target){ return s1; }else if (matrix[row][column] < target) { column++; }else { row--; } } } return s2; } public static void main(String[] args) { int [][]matrix = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; boolean Find = false; int target1 = 1; int target2 = 100; Find = new MianShiTi_3().Find(matrix, target1); System.out.println(Find); System.out.println(new MianShiTi_3().Find2(matrix, target2)); }}
0 0
- 剑指offer(题三)
- 剑指offer题三
- 剑指offer题三:二维数组中的
- 《剑指Offer》做题总结(三)
- 剑指offer 三
- 剑指offer(三)
- 剑指offer题目汇总(三)
- 剑指offer(三)java
- 剑指offer:面试的基础知识(三)
- 剑指offer之编程(三)
- 剑指Offer笔记<JAVA版>(三)
- 剑指offer经典编程(三)
- 剑指offer习题JAVA实现(三)
- 剑指offer 练习三(Java版)
- 剑指offer在线编程(三)
- 剑指Offer编程整理(三)
- 剑指offer之Python练习三
- 剑指offer第一题
- Python 2.7.5 部分中文乱码
- Android--拍照功能的实现
- caffe windows 使用git运行.sh文件
- 一步一步学自定义View(1.简单入门)
- 222. Count Complete Tree Nodes
- 剑指offer(题三)
- 装饰设计模式
- linux环境中用SQL Server?还是MySQL?
- 手把手教你用Git
- div+css的引用形式+定位+浮动
- UDP全双工通信的实现
- React/React Native之状态机原理
- Android学习笔记(七)
- request.getParameter() 和request.getAttribute() 区别