Skip to content
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
25 changes: 25 additions & 0 deletions Problem10.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Time Complexity : O(log N)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

class Solution {
public int findMin(int[] nums) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
if (nums[low] <= nums[high]) {
return nums[low];
}
int mid = low + (high - low)/2;
if((mid == 0 || nums[mid] < nums[mid - 1]) && (mid == nums.length-1 || nums[mid] < nums[mid + 1])){
return nums[mid];
} else if (nums[low] <= nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
24 changes: 24 additions & 0 deletions Problem11.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Time Complexity : O(log N)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

class Solution {
public int findPeakElement(int[] nums) {
int low = 0;
int high = nums.length - 1;

while(low <= high) {
int mid = low + (high - low)/2;

if((mid == 0 || nums[mid] > nums[mid - 1]) && ( mid == nums.length - 1 || nums[mid] > nums[mid + 1])){
return mid;
} else if (nums[mid + 1] > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
51 changes: 51 additions & 0 deletions Problem9.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Time Complexity : O(log N)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

class Solution {
public int[] searchRange(int[] nums, int target) {
int first = firstBinarySearch(nums, target, 0, nums.length-1);
if (first == -1) return new int[]{-1,-1};
int second = secondBinarySearch(nums, target, first, nums.length-1);
return new int[]{first, second};
}

public static int firstBinarySearch(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-1] != target) {
return mid;
} else {
high = mid - 1;
}
} else if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}

public static int secondBinarySearch(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+1] != target) {
return mid;
} else {
low = mid + 1;
}
} else if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
}