LeetCode 33 - Search in Rotated Sorted Array

来源:互联网 发布:服装厂出货软件 编辑:程序博客网 时间:2024/06/08 00:44

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.

You may assume no duplicate exists in the array.

My Code

class Solution {public:    int search(vector<int>& nums, int target) {        int size = nums.size();        int left_idx = 0;        int right_idx = size - 1;        int mid_idx;        int left, mid, right;        while (left_idx <= right_idx)        {            mid_idx = (left_idx + right_idx) / 2;            left = nums[left_idx];            right = nums[right_idx];            mid = nums[mid_idx];            if (target == mid)                return mid_idx;            if (left <= mid)            {                if (mid <= right)                {                    if (target > mid)                        left_idx = mid_idx + 1;                    else                        right_idx = mid_idx - 1;                }                else                {                    if (target > mid)                        left_idx = mid_idx + 1;                    else                    {                        if (target <= right)                            left_idx = mid_idx + 1;                        else                            right_idx = mid_idx - 1;                    }                }            }            else            {                if (target > mid)                {                    if (target <= right)                        left_idx = mid_idx + 1;                    else                        right_idx = mid_idx - 1;                }                else                    right_idx = mid_idx - 1;            }        }        return -1;    }};
Runtime: 6 ms

0 0