leetcode二分查找

二分查找

class Solution {
    public int search(int[] nums, int target) {
        /**
        因为是升序的数组 因此可以使用二分查找法来寻找target
         */
         //避免了超出了数组的边界,还要继续查找的内存消耗
        if (target < nums[0] || target > nums[nums.length-1]) {
            return -1;
        }
        int mid = nums.length/2;
        int begin = 0;
        int end = nums.length-1;

        while (begin <= end) {
            
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[mid] < target) {
                begin = mid + 1;
            }
            else if(nums[mid] > target) {
                end = mid-1;
                
            }
            mid = (begin + end)/2;
        }
        return -1;

        
    }
}

你可能感兴趣的:(leetcode,leetcode,算法,数据结构)