Leetcode-704. 二分查找

C语言题解

int search(int* nums, int numsSize, int target){
    int index = binarySearch(nums,0,numsSize-1,target);
    return index;
}
int binarySearch(int *array,int left,int right,int target){
    int mid = (left + right)/2;
    if(left > right) return -1;
    if(array[mid] == target) return mid;
    if(array[mid] > target){
        right = mid -1;
        return binarySearch(array,left,right,target);
    }else {
        left = mid + 1;
        return binarySearch(array,left,right,target);
    }
}

Java题解

class Solution {
    public int search(int[] nums, int target) {
        int index = binarySearch(nums,0,nums.length-1,target);
        return index;
    }
    public int binarySearch(int[] arr,int left,int right,int target){
        int mid = (left + right)/2;
        if(left > right) return -1;
        if(arr[mid] == target) return mid;
        if(arr[mid] > target){
            right = mid - 1;
            return binarySearch(arr,left,right,target);
        }else {
            left = mid + 1;
            return binarySearch(arr,left,right,target);
        }
    }
}

Javascript题解

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var search = function(nums, target) {
    let left = 0;
    let right = nums.length - 1;
    let mid = -1;
    function binarySearch(left,right){
        if(left > right) return -1;
        mid = Math.floor((left + right)/2);
        if(nums[mid] == target){
            return mid;
        }else if(nums[mid] > target){
            return binarySearch(left,mid - 1);
        }else {
            return binarySearch(mid + 1,right)
        }
    }
    let index = binarySearch(left,right);
    
    return index;
};