Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

162. Find Peak Element

Posted on 2020-05-11 | Edited on 2021-01-22

https://leetcode.com/problems/find-peak-element/

Approach 1: Linear Scan

1
2
3
4
5
6
7
8
class Solution {
public int findPeakElement(int[] nums) {
for(int i=0;i<nums.length-1;i++){
if(nums[i]>nums[i+1]) return i;
}
return nums.length-1;
}
}

Approach 2: Recursive Binary Search

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int findPeakElement(int[] nums) {
return search(nums,0,nums.length-1);
}
public int search(int[] nums,int l,int r){
if(l==r) return l;
int m=l+(r-l)/2;
if(nums[m]>nums[m+1]) return search(nums,l,m);
return search(nums,m+1,r);
}
}

Approach 3: Iterative Binary Search

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int findPeakElement(int[] nums) {
int l=0,r=nums.length-1;
while(l<r){
int m=l+(r-l)/2;
if(nums[m]>nums[m+1]) r=m;
else l=m+1;
}
return l;
}
}

<1…206207208…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%