Search in Rotated Sorted Array II

    Would this affect the run-time complexity? How and why?

    题解

    仔细分析此题和之前一题的不同之处,前一题我们利用这一关键信息,而在此题中由于有重复元素的存在,在A[start] == A[mid]时无法确定有序数组,此时只能依次递增start/递减end以缩小搜索范围,时间复杂度最差变为O(n)。

    1. public class Solution {
    2. /**
    3. * param A : an integer ratated sorted array and duplicates are allowed
    4. * param target : an integer to be search
    5. * return : a boolean
    6. */
    7. if (A == null || A.length == 0) return false;
    8. int lb = 0, ub = A.length - 1;
    9. while (lb + 1 < ub) {
    10. int mid = lb + (ub - lb) / 2;
    11. if (A[mid] > A[lb]) {
    12. // case1: numbers between lb and mid are sorted
    13. if (A[lb] <= target && target <= A[mid]) {
    14. ub = mid;
    15. } else {
    16. lb = mid;
    17. }
    18. } else if (A[mid] < A[lb]) {
    19. if (A[mid] <= target && target <= A[ub]) {
    20. lb = mid;
    21. } else {
    22. }
    23. } else {
    24. // case3: A[mid] == target
    25. lb++;
    26. }
    27. }
    28. if (target == A[lb] || target == A[ub]) {
    29. return true;
    30. }
    31. return false;
    32. }

    最差情况下 O(n), 平均情况下 O(\log n).