码迷,mamicode.com
首页 > 其他好文 > 详细

Search in Rotated Sorted Array

时间:2020-04-04 11:28:53      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:return   else   leetcode   int   ret   targe   tar   ref   sort   

33. Search in Rotated Sorted Array

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = 0, r = nums.size() - 1;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) {
                // target on the left side and mid on the right side
                if (target > nums[r] && nums[mid] < nums[l]) r = mid - 1;
                else l = mid + 1;
            } else {
                // target on the right side and mid on the left side
                if (target < nums[l] && nums[mid] > nums[r]) l = mid + 1;
                else r = mid - 1;
            }
        }
        return -1;
    }
};

Search in Rotated Sorted Array

标签:return   else   leetcode   int   ret   targe   tar   ref   sort   

原文地址:https://www.cnblogs.com/ToRapture/p/12630868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!