Search in Rotated Sorted Array II

来源:互联网 发布:gps软件接收机 编辑:程序博客网 时间:2024/06/22 22:56

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.

class Solution {  public:      bool search(int A[], int n, int target) {          if (A == NULL) {            return NULL;        }                int left = 0;          int right = n - 1;          int mid;                    while (left <= right) {              mid = left + (right - left) / 2;              if (target == A[mid]) {                  return true;              }              else if (A[mid] >= A[left]) {  //对于只有两个元素的                  // left side is sorted                  if (target < A[mid] && target >= A[left]) { //=号                      right = mid - 1;                  }                  else if (target > A[mid] && target <= A[left]) {                      left = mid + 1;                  }                else{                    left = left + 1;                }            }              else if (A[mid] <= A[right]) {                  // right side is sorted                  if (target > A[mid] && target <= A[right]) { //=号                      left = mid + 1;                  }                  else if (target < A[mid] && target >= A[right])  {                      right = mid - 1;                  }                  else {                     right = right - 1;                }            }          }                 return false;    }};



0 0
原创粉丝点击