二分查找-二分查找704-C++

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.empty()) return -1;
        if(nums[0] == target){
            return 0;
        }
        int index0 = 0;
        int index1 = nums.size() - 1;
        int i = (index0 + index1 - 1) / 2;
        while(index0 < index1){
            if(index0 < index1 - 1){
                if(target < nums[i]){
                    index1 = i;
                }else if(target > nums[i]){
                    index0 = i;
                }else{
                    return i;
                }
            }else{
                if(target == nums[index0] || target == nums[index1]){
                    return target == nums[index0] ? index0 : index1;
                }else{
                    return -1;
                }
            }
            i = (index0 + index1) / 2;
        }
        return -1;

    }
};
上一篇:LeetCode167-两数之和II-输入有序数组


下一篇:算法——排序(冒泡排序)