leetcode704 C++ 72ms 二分查找

class Solution {
public:
    int rec(vector<int>& nums, int left, int right, int target){
        int mid = (left + right)/2;
        if(left == right || right-left == 1){
            if(nums[left]==target){
                return left;
            }
            else if(nums[right] == target){
                return right;
            }
            else{
                return -1;
            }
        }
        if(nums[mid] == target){
            return mid;
        }
        else{
            if(nums[mid] < target){
                return rec(nums, mid+1, right, target);
            }
            else{
                return rec(nums, left, mid-1, target);
            }
        }

    }

    int search(vector<int>& nums, int target) {
        if(nums.empty()){
            return -1;
        }
        return rec(nums, 0, nums.size()-1, target);
    }
};
posted @ 2018-08-10 18:40  一条图图犬  阅读(212)  评论(0编辑  收藏  举报