33/81. Search in Rotated Sorted Array I/II(C++)

来源:互联网 发布:对网络的认识和感受 编辑:程序博客网 时间:2024/06/14 23:06

33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

// 总有一边是有序的,用有序的那边作为判断,若不在有序的那边则在另一边class Solution {public:    int search(vector<int>& nums, int target) {        int first = 0, last = nums.size();        while (first != last) { // 直到first和last相等则退出循环            const int mid = first + (last - first) / 2;            if (nums[mid] == target)                return mid;            if(nums[first] <= nums[mid]) {   // 若左半边有序                if (nums[first] <= target && target < nums[mid])                    last = mid; // 缩小范围到左半边                else                    first = mid + 1;// 否则在右半边            } else {  // 若右边有序                if (nums[mid] < target && target <= nums[last - 1])                    first = mid + 1; // 缩小范围到右半边                else                    last = mid; // 否则在左半边            }        }        return -1;    }};

81. 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?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

// 如果A[m] >= A[l]不能确定递增,则拆成两个可能:// (1)若A[m] > A[l],则区间[l,m]一定递增;// (2)若A[m] == A[l],那就l++,往下继续看。class Solution {public:    bool search(vector<int>& nums, int target) {        int first = 0, last = nums.size();        while (first != last) {            const int mid = first + (last - first) / 2;            if (nums[mid] == target)                return true;            if (nums[first] < nums[mid]) {                if (nums[first] <= target && target < nums[mid])                    last = mid;                else                     first = mid + 1;            } else if (nums[first] > nums[mid]) {                if (nums[mid] < target && target <= nums[last-1])                    first = mid + 1;                else                    last = mid;            } else                //skip duplicate one                first++;        }        return false;    }};
原创粉丝点击