LeetCode——033

来源:互联网 发布:javascript 显示隐藏 编辑:程序博客网 时间:2024/06/13 08:28

这里写图片描述
/*
33. Search in Rotated Sorted Array My Submissions QuestionEditorial Solution
Total Accepted: 98590 Total Submissions: 326117 Difficulty: Hard
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.

You may assume no duplicate exists in the array.

Subscribe to see which companies asked this question

*/

/*
解题思路:
旋转数组的元素查找,依然采用折半查找
比非旋转数组多了一层判断

if(右半边有序){
if(target在右半边){
left=mid+1;
}
else{
right=mid-1;
}
//左半边有序
}else{
if(target在左半边){
right=mid-1;
}
else{
left=mid+1;
}
}

*/

class Solution {public:    int search(vector<int>& nums, int target) {        //旋转数组中查找数字,使用折半查找法        if(nums.empty())return -1;        int left=0,right=nums.size()-1;        int mid;        while(left<=right){            mid=left+(right-left)/2;            if(nums[mid]==target)return mid;            //右半边有序            else if(nums[mid]<nums[right]){                if(nums[mid]<target&&nums[right]>=target)left=mid+1;                else right=mid-1;            //左半边有序            }else{                if(nums[mid]>target&& nums[left]<=target)right=mid-1;                else left=mid+1;            }        }        return -1;    }};
0 0
原创粉丝点击