Topic
Follow to "Search in rotated Sorted Array":
What if duplicates is allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given the target was in the array.
Resolution
Compared to the search in rotated Sorted Array, it is necessary to go first, then iterate (recursively) in recursion.
"C + + code"
Class Solution {Public:bool search (int a[], int n, int key) {if (n<=0) return false; if (n==1) {return (A[0]==key)? True:false; } int low=0, high=n-1; while (Low<=high) {if (A[low] < A[high] && (Key < A[low] | | key > A[high]) { return false; }//if dupilicates, them binary search the duplication while (Low < high && A [Low]==a[high]) {low++; } int mid = low + (high-low)/2; if (a[mid] = = key) return true; The target in non-rotated array if (A[low] < A[mid] && key >= A[low] && key< A[mid]) {high = mid-1; Continue }//the target in non-rotated array if (A[mid] < A[high] && key > a[mid] && ke Y <= A[high]) {Low = mid + 1; Continue }//the target in rotated array if (A[low] > A[mid]) {high = mid-1; Continue }//the target in rotated array if (A[mid] > A[high]) {low = mid + 1; Continue }//reach here means nothing found. low++; } return false; }};
"Simple Java Edition"
public class Solution {public Boolean search (int[] A, int target) { int l = 0; int r = a.length-1; while (L <= R) { while (L < r && A[l] = = A[r]) l++ ; int mid = (L + r)/2; if (target = = A[mid]) return true; if (A[l] <= a[r]) { if (target < A[mid]) R = mid-1; else L = mid + 1; } else if (A[l] <= A[mid]) { if (target < a[l] | | target > A[MID]) L = mid + 1; else R = mid-1; } else { if (target < A[mid] | | target > A[R]) r = mid-1; else L = mid + 1; } } return false; }}
Leetcode Search in rotated Sorted Array II problem Solving report