33. Search in Rotated Sorted Array

水题。


class Solution {          
    public:               
        int search(vector<int>& nums, int target) {
            // empty      
            if (nums.empty()) {     
                return -1;
            }             
                          
            // sorted     
            if (nums[0] < nums[nums.size() - 1]) {
                return ssearch(nums, target, 0, nums.size() - 1);
            }             
                          
            // search mid.                                                                                                                                                                                  
            int low = 0;  
            int up = nums.size() - 1;
            int mid = (low + up) >> 1;
            while(low <= up) {      
                if (nums[mid] > nums[nums.size() - 1])  low = mid + 1;
                else                                    up = mid -1;
                mid = (low + up) >> 1;          
            }             
                          
            // search result from part1 or part2.
            int part1_start_idx = 0;
            int part1_end_idx   = low - 1;      
            int part2_start_idx = low;          
            int part2_end_idx   = nums.size() - 1;
            if (target >= nums[0]) {
                return ssearch(nums, target, part1_start_idx, part1_end_idx);
            } else {      
                return ssearch(nums, target, part2_start_idx, part2_end_idx);
            }             
        }                 
                          
        int ssearch(vector<int> nums, int target, int low, int up) {
            int mid = (low + up) >> 1;          
            while(low <= up) {      
                if (nums[mid] < target) low = mid + 1;
                else                    up  = mid -1; 
                mid = (low + up) >> 1;          
            }             
                          
            if (nums[low] == target) {          
                return low;         
            } else {      
                return -1;
            }             
        }                 
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值