Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Done Binary Search 2 #1917

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Problem-1
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//Time Complexity: O(logn)


class Solution {

private int leftSearch(int[] nums,int target,int low, int high)
{
while(low<=high)
{
int mid=low+(high-low)/2;
if(nums[mid]==target)
{
if(mid==0 || nums[mid]!=nums[mid-1])
return mid;
else
high=mid-1;
}
else if(target>nums[mid])
low=mid+1;
else
high=mid-1;

}
return -1;
}
private int rightSearch(int[] nums,int target,int low, int high)
{
while(low<=high)
{
int mid=low+(high-low)/2;
if(nums[mid]==target)
{
if(mid==nums.length-1 || nums[mid]!=nums[mid+1])
return mid;
else
low=mid+1;
}
else if(target>nums[mid])
low=mid+1;
else
high=mid-1;

}
return -1;
}
public int[] searchRange(int[] nums, int target) {
if(nums.length==0)
return new int[]{-1,-1};
int left =leftSearch(nums,target, 0,nums.length-1);
int right;
if(left==-1)
return new int[]{-1,-1};
else
right=rightSearch(nums,target,0,nums.length-1);
return new int[]{left,right};
}
}
22 changes: 22 additions & 0 deletions Problem-2
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//time complexity : O(logn)
class Solution {
public int findMin(int[] nums) {
int low,mid,high;
low=0;
int length=nums.length;
high=nums.length-1;
while(low<=high)
{
mid=low+(high-low)/2;
if(nums[low]<=nums[high])
return nums[low];
else if((mid==0||nums[mid]<nums[mid-1])&& (mid==length-1|| nums[mid]<nums[mid+1]))
return nums[mid];
else if(nums[low]<=nums[mid] )
low=mid+1;
else
high=mid-1;
}
return 0;
}
}
21 changes: 21 additions & 0 deletions Problem-3
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//Time complexity: O(logn)

class Solution {
public int findPeakElement(int[] nums) {
int low,high,mid,length;
length=nums.length;
low=0;
high=length-1;
while(low<=high)
{
mid=low+(high-low)/2;
if((mid==0||nums[mid]>nums[mid-1])&&(mid==length-1||nums[mid]>nums[mid+1]))
return mid;
else if(mid>0&&nums[mid]<nums[mid-1])
high=mid-1;
else
low=mid+1;
}
return 0;
}
}