33. Search in Rotated Sorted Array

来源:互联网 发布:常熟淘宝培训 南天首家 编辑:程序博客网 时间:2024/06/07 09:47

题目

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.

思路

本题数据“亚有序”本来可以用二分查找的,思路就是先用二分法找最小值,时间复杂度log(n),再从最小值及数组首端处或最小值处和数组末端处用二分查找。
但是,比较懒,就直接用了标准库函数

代码

class Solution {public:    int search(vector<int>& nums, int target) {        int index = find(nums.begin(),nums.end(),target)-nums.begin();        return index>=0&&index<nums.size()?index:-1;    }};
原创粉丝点击