-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Solve leetcode problem for binary search. Level medium
- Loading branch information
1 parent
a299baf
commit fbd4824
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
...DsaWithTest/src/main/java/org/practice/dsa/leet_code/medium/bs/SearchInRotatedArray2.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package org.practice.dsa.leet_code.medium.bs; | ||
|
||
public class SearchInRotatedArray2 { | ||
|
||
public static void main(String[] args) { | ||
int[] arr = {1,0,1,1,1}; | ||
int target = 0; | ||
System.out.println(search(arr, target)); | ||
} | ||
|
||
public static boolean search(int[] nums, int target) { | ||
|
||
int start = 0; | ||
int end = nums.length-1; | ||
|
||
while (start <= end) { | ||
int mid = start + (end - start)/2; | ||
|
||
if (nums[mid] == target) { | ||
return true; | ||
} | ||
|
||
if (nums[start] == nums[mid] && nums[end] == nums[mid]) { | ||
start++; | ||
end--; | ||
} else if (nums[start] <= nums[mid]) { | ||
if (target >= nums[start] && target < nums[mid]) { | ||
end = mid - 1; | ||
} else { | ||
start = mid +1; | ||
} | ||
} else { | ||
if (target > nums[mid] && target <= nums[end]) { | ||
start = mid+1; | ||
} else { | ||
end = mid - 1; | ||
} | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
} |