240. Search a 2D Matrix II
Posted hyxsolitude
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了240. Search a 2D Matrix II相关的知识,希望对你有一定的参考价值。
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.
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
.
1 class Solution { 2 class Node { 3 int i, j; 4 int v; 5 public Node(int i, int j, int v) { 6 this.i = i; 7 this.j = j; 8 this.v = v; 9 } 10 } 11 12 static Comparator<Node> cmp = new Comparator<Node>() { 13 public int compare(Node e1, Node e2) { 14 return e1.v - e2.v; 15 } 16 }; 17 18 boolean find(int []value, int target) { 19 int n = value.length; 20 int l = 0, r = n - 1, mid; 21 while (l <= r) { 22 mid = (l + r) / 2; 23 if (value[mid] > target) { 24 r = mid - 1; 25 } else if (value[mid] < target) { 26 l = mid + 1; 27 } else { 28 return true; 29 } 30 } 31 32 return false; 33 34 } 35 36 public boolean searchMatrix(int[][] matrix, int target) { 37 if (matrix.length == 0 || matrix[0].length == 0) return false; 38 Queue<Node> queue = new PriorityQueue<Node>(cmp); 39 queue.add(new Node(0, 0, matrix[0][0])); 40 int [] value = new int[matrix.length * matrix[0].length]; 41 boolean [][] flag = new boolean[matrix.length][matrix[0].length]; 42 int k = 0; 43 while (!queue.isEmpty()) { 44 Node temp = queue.poll(); 45 value[k++] = temp.v; 46 if (temp.i + 1 < matrix.length && !flag[temp.i + 1][temp.j]) { 47 queue.add(new Node(temp.i + 1, temp.j, matrix[temp.i + 1][temp.j])); 48 flag[temp.i + 1][temp.j] = true; 49 } 50 if (temp.j + 1 < matrix[0].length && !flag[temp.i][temp.j + 1] ) { 51 queue.add(new Node(temp.i, temp.j + 1, matrix[temp.i][temp.j + 1])); 52 flag[temp.i][temp.j + 1] = true; 53 } 54 } 55 return find(value, target); 56 } 57 }
以上是关于240. Search a 2D Matrix II的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode]240. Search a 2D Matrix II