Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
404reese authored May 28, 2024
1 parent 75174da commit 0cc4591
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Day20_LeetCode162.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
public int findPeakElement(int[] nums) {
if(nums.length==1){
return 0;
}else if ( nums[0]>nums[1]){
return 0;
}else if ( nums[nums.length-1]>nums[nums.length-2]){
return nums.length-1;
}else {
int start = 1 ;
int end = nums.length-2;
while(start<=end){
int mid = ( start + end)/2;
if(nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1]){
return mid ;
}else if ( nums[mid]<nums[mid+1]){
start = mid+1 ;
}else{
end = mid-1 ;
}
}
return -1 ;
}
}
}
18 changes: 18 additions & 0 deletions Day20_LeetCode162.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
**Day 20: LeetCode 162 [Find Peak Element]**

**Problem Description:**
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.

Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

**Link to LeetCode Problem:**
https://leetcode.com/problems/find-peak-element/description/

**My thought process:**
To implement binary search, we need to initialize the start and end indices to the beginning and end of the array, respectively. We then enter a while loop that continues until start is greater than end. Inside the loop, we calculate the middle index mid and check if nums[mid] is a peak. If it is, we return mid. If it's not, we need to determine on which side of mid the peak lies. If nums[mid] is less than nums[mid+1], it means that the peak lies to the right of mid, so we set start to mid+1. If nums[mid] is less than nums[mid-1], it means that the peak lies to the left of mid, so we set end to mid-1.

0 comments on commit 0cc4591

Please sign in to comment.