33. Search in Rotated Sorted Array

原创 2016年08月30日 23:31:52

这里只会有两种情况


第一种情况下若要找比mid大的值只有往右走,若要找比mid小的值,左右都有可能


第二种情况下若要找比mid小的值只有往左走,若要找比mid大的值,左右都有可能

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



相关文章推荐

leetcode解题之33&81. Search in Rotated Sorted Array java版(在旋转的数字中查找指定值)

33. Search in Rotated Sorted Array ,81. Search in Rotated Sorted Array II 。 leetcode解题之33&81. Search...

leetcode(33). Search in Rotated Sorted Array

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

LeetCode OJ 33 Search in Rotated Sorted Array

难度:hard 由此可见leetcode的hard难度比较于acm是偏简单一些的。 Suppose a sorted array is rotated at some pivot unkn...
  • LLL_mj
  • LLL_mj
  • 2015年07月06日 18:21
  • 298

[leetcode] 33. 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 mig...

Leetcode 33 - Search in Rotated Sorted Array(二分)

题意给一个有序数组,然后从数组的某一个位置,将前后两半交换。现在给一个数k,求k在数组中出现的位置,如果没有出现,返回-1。思路算法1画个图,其实就两种情况:前半段长还是后半段长,然后分若干种情况去讨...
  • Lzedo
  • Lzedo
  • 2017年02月13日 16:44
  • 88

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

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

【C++】【LeetCode】33. Search in Rotated Sorted Array

题目Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i...
  • zjajgyy
  • zjajgyy
  • 2017年06月11日 15:51
  • 77

LeetCode33——Search in Rotated Sorted Array

LeetCode33——Search in Rotated Sorted Array 简单来说就是在数组中查找  输入的  target,如果找到返回索引,如果没有找到返回-1 在中S...

LeetCode: 33. Search in Rotated Sorted Array

LeetCode: 33. Search in Rotated Sorted Array

[Leetcode]33(81). Search in Rotated Sorted Array I, II

题目大意: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:33. Search in Rotated Sorted Array
举报原因:
原因补充:

(最多只允许输入30个字)