Find Peak Element BS LeetCode
unknown
java
4 months ago
986 B
5
Indexable
class Solution { public int findPeakElement(int[] nums) { if(nums.length==1){ return 0; } int low = 0, high = nums.length-1; while(low<=high){ int mid = (low+high)/2; int checkVal = check(nums, mid); if(checkVal==0){ return mid; } else if (checkVal ==1){ low=mid+1; } else{ high=mid-1; } } return -1; } private int check(int[] nums, int idx){ int n= nums.length; int lowerIdx = idx-1; int higherIdx = idx+1; if(lowerIdx == -1){ return (nums[idx]>nums[higherIdx]) ? 0 : 1; } if(higherIdx == n){ return (nums[idx]>nums[lowerIdx]) ? 0 : -1; } if(nums[idx]<nums[lowerIdx]){ return -1; } if(nums[idx]<nums[higherIdx]){ return 1; } return 0; } }
Editor is loading...
Leave a Comment