Last active
August 9, 2020 14:18
-
-
Save bittib/5676076 to your computer and use it in GitHub Desktop.
Search In Rotated Sorted Array II Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array.
This file contains hidden or 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
public boolean search(int[] A, int target) { | |
int low = 0, high = A.length-1; | |
while (low <= high){ | |
while (low < high && A[low] == A[high]) | |
high--; | |
int mid = low + (high - low)/2; | |
if (A[mid] == target) | |
return true; | |
if (A[low] <= A[mid]){ | |
if (A[low] <= target && target < A[mid]) | |
high = mid-1; | |
else | |
low = mid+1; | |
}else if (A[mid] <= A[high]){ | |
if (A[mid] < target && target <= A[high]) | |
low = mid+1; | |
else | |
high = mid-1; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice article. I found this article highly explanatory covering the minute details. If you are interested, check this out - https://algopro.in/questions/category/array/search-in-a-sorted-array.