leetcode-题4-2

因为有重复元素,所以不能通过左边边界>=中间边界确定上升序列,所以通过将左边边界>=分解为两个条件,左边边界>中间---认为左边一定升序,左边<中间--认为右边一定
升序,想等的可以左边++;


class Solution { public: bool search(int A[], int n, int target) { int first = 0, last = n; while (first != last) { const int mid = (first + last) / 2; if (A[mid] == target) return true; if (A[first] < A[mid]) { if (A[first] <= target && target < A[mid]) last = mid; else first = mid + 1; } else if (A[first] > A[mid]) { if (A[mid] < target && target <= A[last-1]) first = mid + 1; else last = mid; } else //和中点相等直接++ first++; } return false; } };

  

posted @ 2017-05-23 14:17  babyking1  阅读(140)  评论(0编辑  收藏  举报