competitive-programmingDec 29, 20211 min read

[LeetCode] 162. Find Peak Element Explained

Updated: Dec 29, 2021

Binary search
Available in:enko

#Problem

162. Find Peak Element

#Approach

Use binary search to compare nums[m]nums[m] with the values on either side.

  1. If nums[m1]>nums[m]nums[m-1] \gt nums[m]:
    a peakpeak exists to the left of index mm.
r <- m;
  1. If nums[m]<nums[m+1]nums[m] \lt nums[m+1]:
    a peakpeak exists to the right of index mm.
l <- m+1;
  1. If neither holds: index mm itself is a peakpeak.
return m;

#Code

/**
 * written: 2021. 12. 29. Wed. 16:05:01 [UTC+9]
 * jooncco의 mac에서.
 **/

typedef vector<int> vi;

class Solution {
public:
    int findPeakElement(vi &nums) {
        int n= nums.size();
        // nums[-1]과 nums[n]이 -∞ 이므로 size가 1이면 자체가 peak
        if (n == 1) return 0;

        int l= 0, r= n-1;
        while (l < r) {
            int m= l+(r-l)/2;
            if (m > 0 && nums[m] < nums[m-1]) r= m;
            else if (m < n-1 && nums[m] < nums[m+1]) l= m+1;
            else return m;  // peak를 찾았으니 바로 return.
        }
        // l == peak index
        return l;
    }
};

#Complexity

  • Time: O(logn)O(\log n)
  • Space: O(1)O(1)