leetcode 33|81. Search in Rotated Sorted Array 1|2

来源:互联网 发布:java工程师面试题 编辑:程序博客网 时间:2024/06/01 07:47

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)     {        if (nums.empty())            return -1;        int left = 0;        int right = nums.size() - 1;        int mid;                  while (left + 1 < right)        {            mid = (right - left) / 2 + left;                     if (nums[mid] == target)                return mid;            else if (nums[left] <= nums[mid])            {                if (nums[left] <= target && target <= nums[mid])                    right = mid;                else                    left = mid;            }            else            {                if (nums[left] <= target || target <= nums[mid])                    right = mid;                else                    left = mid;            }        }        //double check        if (nums[left] == target)            return left;        else if (nums[right] == target)            return right;        else             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],[l,m]是递增元素的条件就不成立。
       如果a[m]=a[l],l++

class Solution {public:    bool search(vector<int>& nums, int target)     {        if (nums.empty()) return false;        int l = 0;        int r = nums.size() - 1;        while (l + 1 < r)        {            int m = ( r - l ) / 2 + l;            if (nums[m] == target)                return true;            else if (nums[l] < nums[m])            {                if (target >= nums[l] && target < nums[m])                    r = m;                else                    l = m;            }            else if (nums[l] == nums[m]) //关键,必须保证[l,m]是递增元素            {                l++;            }            else            {                if (target >= nums[l] || target < nums[m])                    r = m;                else                    l = m;            }        }        //double check        return nums[l] == target || nums[r] == target;     }};
















阅读全文
0 0