[LeetCode] Search in Rotated Sorted Array II 在旋轉有序陣列中搜索之二
阿新 • • 發佈:2018-12-27
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.
這道是之前那道 Search in Rotated Sorted Array 在旋轉有序陣列中搜索 的延伸,現在陣列中允許出現重複數字,這個也會影響我們選擇哪半邊繼續搜尋,由於之前那道題不存在相同值,我們在比較中間值和最右值時就完全符合之前所說的規律:如果中間的數小於最右邊的數,則右半段是有序的,若中間數大於最右邊數,則左半段是有序的
class Solution { public: bool search(int A[], int n, int target) { if (n == 0) returnfalse; int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (A[mid] == target) return true; else if (A[mid] < A[right]) { if (A[mid] < target && A[right] >= target) left = mid + 1; else right = mid - 1; } else if (A[mid] > A[right]){ if (A[left] <= target && A[mid] > target) right = mid - 1; else left = mid + 1; } else --right; } return false; } };