peak element in an array = > Binary Search
A peak element is an element that is greater than its neighbors
Given an input array where num[i] != num[i+1], find a peak element and return its index.
Imagine num[-1] = num[n] = -INF
s= [1,2,3,1]
Return index number 2 where 3 is a peak element
2. Implementation
Q1: peak element ? global or local?
A1: greater than its neighbors , local maximum
Q1: multiple peaks ?
A1: return any of them
Q1: how to find peak?
A1: [0] > [1] or not, [n-1] > [n-1] or not
i =1~ n-2
[i] > [i-1] && [i] > [i+1]
[1,2,3,1]
i=0 1 > 2 X
i=1 2 >1 , 2 <3 X
i=2 3>2, 3 >1 O
i=3 1 > 3X
// Time:O(log(n)) public int findPeakElement(int[] nums) { if (nums.length == 0|| nums == null) return -1; int l = 0; int r = nums.length -1; while (l <= r) { if (l == r) return l; int m = (l+r) >>1; if ( nums[m] > nums[m+1] ) //3 >2 r = m; else // 1 < 3 l = m+1; } return l; }
// Time: O(n) public int findPeakElement(int[] nums) { // validate the input if ( nums == null || nums.length == 0) return -1; //for (int i = 0; i < nums.length -1; i++) //{ // if( i==0 && nums[i] > nums[i+1]) // return i; // else if (i == num.length-1 && nums[i] > nums[i-1]) // return i; // else if (i>0 && i < nums.length-1 && nums[i] > nums[i-1] && nums[i] > nums[i+1]) // return i; //} // NOTE: nums[0] as first comparison to save a iterating index and csn separate from index 1 to len-2 int max = num[0]; int index = 0; for (int i = 1; i < num.length -1; i++) { int cur = nums[i]; int prev= nums[i-1]; int next = nums[i+1]; if ( cur > prev && cur > next && cur > max) { max = cur; index = i; } } if (max < nums[nums.length -1]) return nums.length -1; return index; }3. Similar ones
[Binary Search] Search for a Range
[Binary Search] Search in Rotated Sorted Array I /II
[Binary Search] Search a 2D Matrix
[Binary Search] Search Insert Position
Find ... Element
No comments:
Post a Comment