LeetCode Online Judge 题目C# 练习 - 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.
1 public static bool SearchinRotatedSortedAarrayII(int[] A, int target) 2 { 3 return BinarySearchRotatedSortedArrayII(A, 0, A.Length - 1, target); 4 } 5 6 public static bool BinarySearchRotatedSortedArrayII(int[] A, int l, int r, int target) 7 { 8 if (l > r) 9 return false; 10 11 int m = (l + r) / 2; 12 13 if (target == A[m]) 14 return true; 15 16 // if duplicate is allowed, we have to search both upper and lower halves 17 // corner case : 8,9,5,8,8,8,8,8 and 8,8,8,8,9,5,8 18 if (A[m] == A[l] && A[m] == A[r]) 19 { 20 return BinarySearchRotatedSortedArrayII(A, l, m - 1, target) || 21 BinarySearchRotatedSortedArrayII(A, m + 1, r, target); 22 } 23 24 if (A[m] >= A[l]) 25 { 26 if (target >= A[l] && target < A[m]) 27 r = m - 1; 28 else 29 l = m + 1; 30 31 return BinarySearchRotatedSortedArrayII(A, l, r, target); 32 } 33 else 34 { 35 if (target > A[m] && target <= A[r]) 36 l = m + 1; 37 else 38 r = m - 1; 39 40 return BinarySearchRotatedSortedArrayII(A, l, r, target); 41 } 42 43 }
代码分析:
如注释里说的,如果允许重复,那就要前半部后半部都要找。 我承认,我掉入陷阱里了!!! 如果数组全是 0 , 要你找1. 那么时间复杂度是多少?O(n)吧。既然是O(n),干嘛不就loop一遍呢?
1 public static bool SearchinRotatedSortedAarrayIIOpt(int[] A, int target) 2 { 3 for (int i = 0; i < A.Length; i++) 4 { 5 if (A[i] == target) 6 return true; 7 } 8 return false; 9 }