Skip to content

1901. Find a Peak Element II 👍

  • Time: $O(n\log m)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  vector<int> findPeakGrid(vector<vector<int>>& mat) {
    int l = 0;
    int r = mat.size() - 1;

    while (l < r) {
      const int m = (l + r) / 2;
      if (ranges::max(mat[m]) >= ranges::max(mat[m + 1]))
        r = m;
      else
        l = m + 1;
    }

    return {l, getMaxIndex(mat[l])};
  }

 private:
  int getMaxIndex(const vector<int>& A) {
    pair<int, int> res{0, A[0]};
    for (int i = 1; i < A.size(); ++i)
      if (A[i] > res.second)
        res = {i, A[i]};
    return res.first;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int[] findPeakGrid(int[][] mat) {
    int l = 0;
    int r = mat.length - 1;

    while (l < r) {
      final int m = (l + r) / 2;
      if (Arrays.stream(mat[m]).max().getAsInt() >= Arrays.stream(mat[m + 1]).max().getAsInt())
        r = m;
      else
        l = m + 1;
    }

    return new int[] {l, getMaxIndex(mat[l])};
  }

  private int getMaxIndex(int[] A) {
    int[] res = {0, A[0]};
    for (int i = 1; i < A.length; ++i)
      if (A[i] > res[1])
        res = new int[] {i, A[i]};
    return res[0];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def findPeakGrid(self, mat: List[List[int]]) -> List[int]:
    l = 0
    r = len(mat) - 1

    while l < r:
      m = (l + r) // 2
      if max(mat[m]) >= max(mat[m + 1]):
        r = m
      else:
        l = m + 1

    return [l, mat[l].index(max(mat[l]))]