Search a 2D Matrix II(leetcode)
来源:互联网 发布:神仙道懒娃 源码 编辑:程序博客网 时间:2024/06/07 06:53
Search a 2D Matrix II
- Search a 2D Matrix II
- 题目
- 解决
- 规律解决
题目
leetcode题目
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true
.
Given target = 20, return false
.
解析:我们需要解决的是知道给定的二维数组array和目标数target,判断target是否在array里面。而且给定的array中数与数之间是存在这样的规律——array[i][j] < array[i][j+1]
和 array[i][j] < array[i+1][j]
,因此我们可以根据这个规律解决问题。
解决
规律解决
规律:array[i][j] < array[i][j+1]
和 array[i][j] < array[i+1][j]
我们可以每次将target同array[i][column]
(column是array的列数)进行比较,判断target是否在array的这一行或者上一行。
复杂度为O(row+column)。
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int row = matrix.size(); if (row == 0) { return false; // 数组为空时,自然返回false } int column = matrix[0].size(); int i = 0; // 从第一行可是扫描数组 int j = column - 1; while (i < row && j >= 0) { if (matrix[i][j] == target) { return true; } else if (matrix[i][j] < target) { i++; // target可能在下一行 } else { j--; // target可能在这一行 } } return false; }};
leetcode结果:129 / 129 test cases passed. Runtime: 66 ms
- #leetcode#Search a 2D Matrix II
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [Leetcode]Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode || Search a 2D Matrix II
- LeetCode----Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- *LeetCode-Search a 2D Matrix II
- Search a 2D Matrix II -- leetcode
- leetcode | Search a 2D Matrix II
- 【算法研究与实现】最小二乘法直线拟合
- 17:Letter Combinations of a Phone Number(字母组合的电话号码)
- count,sum,avg,max,min__mysql学习笔记
- C++中 typename 和 class 的区别
- SpringMVC小结
- Search a 2D Matrix II(leetcode)
- 重载 重写
- 最简单的排序——选择排序
- 城市交通
- spring,springmvc,mybatits集成实例--后台分页查询
- idea安装与使用
- J
- fastDFS与Java整合上传下载
- c文件和h文件的区别