码迷,mamicode.com
首页 > 其他好文 > 详细

81. Search in Rotated Sorted Array II

时间:2016-05-07 09:36:39      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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.

这个题目是在https://leetcode.com/problems/search-in-rotated-sorted-array/
的基础上,添加了允许有相同的元素这个条件。
那么就会有一种特殊情况,比如1,1,1,1,1,3,3 旋转之后为1,3,3,1,1,1,1.
当中间的元素等于第一个元素时,就把l++,因为target!=nums[mid]的
而nums[mid]=nums[l],可以推出target!=nums[l]。

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int l=0,r=nums.size()-1;
        while(l<=r){
            int mid=(l+r)/2;
            if(nums[mid]==target)
                return true;
            else if(nums[mid]>nums[l]){//递增的序列在左边
                if(target>=nums[l]&&target<nums[mid])
                    r=mid-1;
                else
                    l=mid+1;
            }else if(nums[mid]<nums[l]){
                if(target>nums[mid]&&target<=nums[r])
                    l=mid+1;
                else
                    r=mid-1;
            }else if(nums[mid]==nums[l]){
                l++;
            }
        }
        return false;
    }
};

而 Search in Rotated Sorted Array
Suppose a sorted array 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.
这个题目 只需要把返回的参数改一下就可以AC了。

class Solution {
public:
    int search(vector<int>& nums, int target) {
          int l=0,r=nums.size()-1;
        while(l<=r){
            int mid=(l+r)/2;
            if(nums[mid]==target)
                return mid;
            else if(nums[mid]>nums[l]){
                if(target>=nums[l]&&target<nums[mid])
                    r=mid-1;
                else
                    l=mid+1;
            }else if(nums[mid]<nums[l]){
                if(target>nums[mid]&&target<=nums[r])
                    l=mid+1;
                else
                    r=mid-1;
            }else if(nums[mid]==nums[l]){
                l++;
            }
        }
        return -1;
    }
};

81. Search in Rotated Sorted Array II

标签:

原文地址:http://blog.csdn.net/a342500329a/article/details/51333521

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!