LeetCode 1901. Find a Peak Element II
原题链接在这里:https://leetcode.com/problems/find-a-peak-element-ii/
题目:
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.
Given a 0-indexed m x n
matrix mat
where no two adjacent cells are equal, find any peak element mat[i][j]
and return the length 2 array [i,j]
.
You may assume that the entire matrix is surrounded by an outer perimeter with the value -1
in each cell.
You must write an algorithm that runs in O(m log(n))
or O(n log(m))
time.
Example 1:
Input: mat = [[1,4],[3,2]] Output: [0,1] Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
Example 2:
Input: mat = [[10,20,15],[21,30,14],[7,16,32]] Output: [1,1] Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 500
1 <= mat[i][j] <= 105
- No two adjacent ce lls are equal.
题解:
Find the middle column, within middle column, find the biggest row, maxRow.
Now we are sure maxRow element is bigger than up and down.
Then check left and right. If maxRow middle column eleemnt is bigger than left and right, then it is peak element.
If it is smaller than left, then peak element must be on the left. Otherwise, on the right.
Time Complexity: O(mlogn). m = mat.length. n = mat[0].length.
Space: O(1).
AC Java:
1 class Solution { 2 public int[] findPeakGrid(int[][] mat) { 3 if(mat == null || mat.length == 0 || mat[0].length == 0){ 4 return new int[]{-1, -1}; 5 } 6 7 int m = mat.length; 8 int n = mat[0].length; 9 int l = 0; 10 int r = n - 1; 11 while(l <= r){ 12 int mid = l + (r - l) / 2; 13 int maxRow = 0; 14 for(int i = 0; i < m; i++){ 15 if(mat[i][mid] > mat[maxRow][mid]){ 16 maxRow = i; 17 } 18 } 19 20 int left = mid == 0 ? -1 : mat[maxRow][mid - 1]; 21 int right = mid == n - 1 ? -1 : mat[maxRow][mid + 1]; 22 if(left < mat[maxRow][mid] && mat[maxRow][mid] > right){ 23 return new int[]{maxRow, mid}; 24 }else if(left > mat[maxRow][mid]){ 25 r = mid - 1; 26 }else{ 27 l = mid + 1; 28 } 29 } 30 31 return new int[]{-1, -1}; 32 } 33 }