LeetCode - 240. Search a 2D Matrix II
2016-06-30 11:09
375 查看
矩阵中两行或者两列之间的元素的大小并没有一定的规律,所以二分法不太好用,直接用74. Search a 2D Matrix的解法二即可,时间复杂度为O(n + m),代码如下:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int i = 0;
int j = cols - 1;
while(i < rows && j >= 0){
if(matrix[i][j] == target){
return true;
}else if(matrix[i][j] < target){
i++;
}else{
j--;
}
}
return false;
}
}
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int i = 0;
int j = cols - 1;
while(i < rows && j >= 0){
if(matrix[i][j] == target){
return true;
}else if(matrix[i][j] < target){
i++;
}else{
j--;
}
}
return false;
}
}
相关文章推荐
- C#使用Matrix执行缩放的方法
- 如何使用Matrix对bitmap的旋转与镜像水平垂直翻转
- 如何利用matrix实现图片倒影效果
- Android中Matrix用法实例分析
- Android中使用Matrix控制图形变换和制作倒影效果的方法
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- HP Z800 Workstation - Configuring RAID devices (HP Z800 做磁盘Raid1,Raid0的阵列)
- Android Matrix类以及ColorMatrix类详解
- leetcode----Longest Substring Without Repeating Characters
- 用css实现图片的旋转
- 让舞台上的按钮btn灰掉
- Android中Bitmap和Drawable
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum