LeetCode Online Judge 题目C# 练习 - Search a 2D Matrix
2012-10-16 22:25
489 查看
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.
代码分析:
先往下,不能往下就往右。
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 static bool Searcha2DMatrix(List<List<int>> matrix, int target) { int i = 0, j = 0; while (i < matrix.Count && j < matrix[i].Count) { if (matrix[i][j] == target) return true; if (i + 1 < matrix.Count && matrix[i + 1][j] <= target) i++; else if (j + 1 < matrix[i].Count && matrix[i][j + 1] <= target) j++; else return false; } return false; }
代码分析:
先往下,不能往下就往右。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees
- LeetCode Online Judge 题目C# 练习 - Sparial Matrix II
- LeetCode Online Judge 题目C# 练习 - Search for a Range
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Longest Common Prefix
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array
- LeetCode Online Judge 题目C# 练习 - Set Matrix Zeroes
- LeetCode Online Judge 题目C# 练习 - Container With Most Water
- LeetCode Online Judge 题目C# 练习 - Longest Palindromic Substring
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Restore IP Addresses
- LeetCode Online Judge 题目C# 练习 - Simplify Path
- LeetCode Online Judge 题目C# 练习 - Sqrt(x)
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List
- LeetCode Online Judge 题目C# 练习 - Substring with Concatenation of All Words
- LeetCode Online Judge 题目C# 练习 - Palindrome Number
- LeetCode Online Judge 题目C# 练习 - Rotate List
- LeetCode Online Judge 题目C# 练习 - Sudoku Solver