Find Peak Element II

Given an integer matrix A which has the following features :

  • The numbers in adjacent positions are different.
  • The matrix has n rows and m columns.
  • For all i < nA[i][0] < A[i][1] && A[i][m - 2] > A[i][m - 1].
  • For all j < mA[0][j] < A[1][j] && A[n - 2][j] > A[n - 1][j]

We define a position [i, j] is a peak if:

  A[i][j] > A[i + 1][j] && A[i][j] > A[i - 1][j] && 
  A[i][j] > A[i][j + 1] && A[i][j] > A[i][j - 1]

Find a peak element in this matrix. Return the index of the peak.

Example

Example 1:

Input: 
    [
      [1, 2, 3, 6,  5],
      [16,41,23,22, 6],
      [15,17,24,21, 7],
      [14,18,19,20,10],
      [13,14,11,10, 9]
    ]
Output: [1,1]
Explanation: [2,2] is also acceptable. The element at [1,1] is 41, greater than every element adjacent to it.

Example 2:

Input: 
    [
      [1, 5, 3],
      [4,10, 9],
      [2, 8, 7]
    ]
Output: [1,1]
Explanation: There is only one peek.

Challenge

Solve it in O(n+m) time.

If you come up with an algorithm that you thought it is O(nlogm) or O(mlogn), can you prove it is actually O(n+m) or propose a similar but O(n+m) algorithm?

Notice

Guarantee that there is at least one peak, and if there are multiple peaks, return any one of them.

思路:对列进行二分,然后每一行扫描,nlog(m)

public class Solution {
    /*
     * @param A: An integer matrix
     * @return: The index of the peak
     */
    public List<Integer> findPeakII(int[][] A) {
        List<Integer> list = new ArrayList<Integer>();
        if(A == null || A.length == 0 || A[0].length == 0) {
            return list;
        }
        
        for(int i = 0; i < A.length; i++) { // 注意,这里是一层循环。
            int j = findPeak(A[i]);
            if(isvalid(A, i, j)) {
                list.add(i);
                list.add(j);
                break;
            }
        }
        return list;
    }
    
    public boolean isvalid(int[][] A, int i, int j) {
        int n = A.length;
        int m = A[0].length;
        return (0 <= i-1 && i+1 < n && 0 <= j-1 && j+1 < m && 
                A[i][j] > A[i+1][j] && A[i][j] > A[i-1][j] 
                && A[i][j] > A[i][j+1] && A[i][j] > A[i][j-1]);
    }
    
    private int findPeak(int[] A) {
        int start = 1; int end = A.length - 2;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(A[mid] > A[mid+1]) {
                end = mid;
            } else {
                start = mid;
            }
        }
        
        if(A[start] > A[end]) {
            return start;
        }
        return end;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值