LeetCode 74(Search a 2D Matrix)Java
2016-12-01 09:33
471 查看
原题:Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties
1. Integers in each row are sorted from left to right.
2. The first integer of each row is greater than the last integer of the previous row.
给定一个m x n的矩阵,该矩阵满足如下性质:
1. 矩阵每一行的元素已经按从小到大的顺序排好序;
2. 矩阵每一行的任意一个元素都大于它上面行的任意一个元素;
思路:
面对一个在横向和纵向都是排好序的矩阵,我们不必采用依次查找的算法(复杂度O(m*n)),可以采用两次二分法,先找到对应行的索引,再在该行内进行二分查找(复杂度O(logm)*O(logn)),判断该数是否存在。
代码:
This matrix has the following properties
1. Integers in each row are sorted from left to right.
2. The first integer of each row is greater than the last integer of the previous row.
给定一个m x n的矩阵,该矩阵满足如下性质:
1. 矩阵每一行的元素已经按从小到大的顺序排好序;
2. 矩阵每一行的任意一个元素都大于它上面行的任意一个元素;
思路:
面对一个在横向和纵向都是排好序的矩阵,我们不必采用依次查找的算法(复杂度O(m*n)),可以采用两次二分法,先找到对应行的索引,再在该行内进行二分查找(复杂度O(logm)*O(logn)),判断该数是否存在。
代码:
/* Author:Jassy Time:2016/11/30 Number:LeetCode 74 Resource:https://leetcode.com/problems/search-a-2d-matrix/ Result:AC Conclusion: */ public class Solution { boolean flag=false; public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length==0){ return false; } int[] index=new int[matrix.length]; for(int i=0;i<index.length;i++){ index[i]=matrix[i][0]; } int count1=binarySearch(index,target); int count2=binarySearch(matrix[count1],target); if(flag==true){ return true; }else{ return false; } } int binarySearch(int[] nums,int target){ int left=0; int right=nums.length-1; int mid=0; while(left<=right){ mid=(left+right)/2; if(target>nums[mid]){ left=mid+1; }else if(target<nums[mid]){ right=mid-1; }else{ flag=true; return mid; } } return (left+right)/2; } }
相关文章推荐
- LeetCode 74 Search a 2D Matrix with java solution
- (java)leetcode74:Search a 2D Matrix
- leetcode JAVA Search a 2D Matrix 难度系数3 3.25
- [leetcode 74] Search a 2D Matrix
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】
- Java for LeetCode 074 Search a 2D Matrix
- leetcode 74 : Search a 2D Matrix
- Search a 2D Matrix leetcode java
- [LeetCode][Java] Search a 2D Matrix
- LeetCode(74) Search a 2D Matrix
- [leetcode-74]Search a 2D Matrix(c)
- Leetcode 74 Search a 2D Matrix
- [Leetcode 62] 74 Search a 2D Matrix
- leetcode[74]Search a 2D Matrix
- [LeetCode]74 Search a 2D Matrix
- [Leetcode 74, medium] Search a 2D Matrix
- leetcode || 74、Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- LeetCode(74) Search a 2D Matrix
- leetcode 74: Search a 2D Matrix