码迷,mamicode.com
首页 > 编程语言 > 详细

【剑指offer】Java实现

时间:2018-01-13 23:54:04      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:int   size   遍历   查找   str   leetcode   closed   简单的   面试题   

面试题3 二维数组中的查找 Leetcode--74 Search a 2D Matrix

 

技术分享图片
 1 /*Java
 2 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
 3 
 4     Integers in each row are sorted from left to right.
 5     The first integer of each row is greater than the last integer of the previous row.
 6 
 7 For example,
 8 
 9 Consider the following matrix:
10 
11 [
12   [1,   3,  5,  7],
13   [10, 11, 16, 20],
14   [23, 30, 34, 50]
15 ]
16 
17 Given target = 3, return true.
18 本题最简单的方法循环遍历行与列 但是时间复杂度较高。
19 */
20 class Solution {
21     public boolean searchMatrix(int[][] matrix, int target) {
22         boolean find = false;
23         int rows,cols;
24         if (matrix == null || matrix.length==0) {
25             rows = 0;
26             cols = 0;
27         } else {
28             rows = matrix.length;
29             cols = matrix[0].length;
30         }
31             
32         if (matrix != null && rows > 0 && cols > 0) {
33             int row = 0;
34             int col = cols-1;
35             while(row<rows && col>=0){
36                 if(matrix[row][col]==target){
37                     find=true;
38                     break;
39                 }
40                     
41                 else if(matrix[row][col]>target){
42                     col--;
43                 }else{
44                     row++;
45                 }
46             }
47         }
48 
49         return find;
50     }
51 public static void main(String[] args) {
52         int[][] matrix1 = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
53 
54         int[][] matrix = {};
55         int target = 55;
56         SearchA2DMatrix cc = new SearchA2DMatrix();
57         boolean find = cc.searchMatrix(matrix, target);
58         System.out.println(find);
59     }
60 }
View Code

 

【剑指offer】Java实现

标签:int   size   遍历   查找   str   leetcode   closed   简单的   面试题   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8280622.html

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