LeetCode--No.74--Search a 2D Matrix
来源:互联网 发布:程序员联合开发王 编辑:程序博客网 时间:2024/05/16 09:50
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3
, return true
.
我的代码:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix == null) return false; int m = matrix.length; int n = matrix[0].length; if (m < 1 || n < 1) return false; int start = 0; int end = m - 1; int row_index = 0; while(start <= end){ int mid = (start + end) / 2; if (target < matrix[mid][0]) end = mid - 1; else if (target > matrix[mid][n - 1]) start = mid + 1; else{ row_index = mid; break; } } start = 0; end = n - 1; while(start <= end){ int mid = (start + end) / 2; if (target == matrix[row_index][mid]) return true; else if (target < matrix[row_index][mid]) end = mid - 1; else start = mid + 1; } return false; }}
就是两个,二分查找。时间复杂度没问题。都是O(logn). 然而看了下别人的代码才发现自己的写的有多不简洁。
就是感觉思维还是很定式。觉得按顺序的查找,肯定是二分。那二维的自然就是两次二分。然而其实不需要。大可以把二维数组当做一维。
下面是优化后的代码-- 抄自 leetcode solution part
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) return false; int start = 0, rows = matrix.length, cols = matrix[0].length; int end = rows*cols - 1; while(start <= end){ int mid = (start + end) / 2; if (matrix[mid/cols][mid%cols] == target) return true; if (matrix[mid/cols][mid%cols] < target) start = mid + 1; else end = mid - 1; } return false; }}
我今天真的撑死了。
我要坚持住早起去健身房锻炼。我要成为健康的宝宝。撑死我了。
再刷两道题消化消化,再去吃冻酸奶!
0 0
- Leetcode NO.74 Search a 2D Matrix
- Leetcode No.74 Search a 2D Matrix
- LeetCode--No.74--Search a 2D Matrix
- LeetCode No.240 Search a 2D Matrix II
- LeetCode No.240 Search a 2D Matrix II
- Leetcode 74 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
- leetcode || 74、Search a 2D Matrix
- leetcode-74 Search a 2D Matrix
- Leetcode[74]-Search a 2D Matrix
- 【Leetcode】Search a 2D Matrix #74
- LeetCode(74) Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- leetcode 74: Search a 2D Matrix
- 散列表1: 基于分离链接法的散列表
- java算法知识点解析(1):字符串操作
- Linq:对XML文档进行增、删、改、查询(一)
- Maven中的dependency的scope作用域详解
- markdown 设置字体、字号、颜色以及背景色
- LeetCode--No.74--Search a 2D Matrix
- linux(Centos)修改主机名的方法
- Linux初识(二)
- JavaScript--6.事件处理
- 使用FreeMarker生成静态HTML
- iOS Runtime介绍
- Senparc.Weixin框架开发-发消息没有回应的处理办法
- Freemarker的加载模板目录
- 通过金矿模型介绍动态规划