33. Search in Rotated Sorted Array

来源:互联网 发布:mysql 添加分区出错 编辑:程序博客网 时间:2024/06/06 05:53

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.

这道题其实应该用二分搜索来做比较好,可以参考discuss中的那些方法。我的思路是,若target大于nums[0],就从前往后搜,遇到变小的数时,就停止搜索。若target小于nums[0],就从后往前搜,遇到变大的数就停止搜索,这个方法也可以通过。

class Solution {public:    int search(vector<int>& nums, int target) {        if (nums.empty()) return -1;        if (target >= nums[0]) {            for (int i = 0; i < nums.size(); i++) {                if (target == nums[i]) return i;                if (i != 0 && nums[i] < nums[i - 1]) return -1;            }        }        else {            for (int i = nums.size() - 1; i >= 0; i--) {                if (target == nums[i]) return i;                if (i != nums.size() - 1 && nums[i] > nums[i + 1]) return -1;            }        }        return -1;    }};
原创粉丝点击