Last active
August 29, 2015 14:22
-
-
Save cangoal/04062060e67733d3057f to your computer and use it in GitHub Desktop.
LeetCode - Find Peak Element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public int findPeakElement(int[] nums) { | |
| if(nums==null || nums.length==0) return -1; | |
| if(nums.length == 1) return 0; | |
| for(int i=0; i < nums.length; i++){ | |
| if(i==0 && nums[i] > nums[i+1] || i==nums.length-1 && nums[i] > nums[i-1]) return i; | |
| if(nums[i] > nums[i+1] && nums[i] > nums[i-1]) return i; | |
| } | |
| return -1; | |
| } | |
| // | |
| public int findPeakElement(int[] num) { | |
| int left=0, right=num.length-1; | |
| while(left<right){ | |
| int mid = (left+right)/2; | |
| int mid2 = mid+1; | |
| if(num[mid]>num[mid2]){ | |
| right=mid; | |
| } | |
| else{ | |
| left=mid+1; | |
| } | |
| } | |
| return left; | |
| } | |
| // | |
| public int findPeakElement(int[] num) { | |
| for(int i=1; i<num.length; i++){ | |
| if(num[i] < num[i-1]){ | |
| return i-1; | |
| } | |
| } | |
| return num.length-1; | |
| } | |
| // binary search | |
| public int findPeakElement(int[] nums) { | |
| if(nums==null || nums.length == 0) return -1; | |
| int left = 0, right = nums.length-1; | |
| while(left < right){ | |
| int mid = (left + right) / 2; | |
| if(nums[mid] < nums[mid+1]) left = mid+1; | |
| else right = mid; | |
| } | |
| return left; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment