leetcode (Binary Search)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/86215700

Title:Binary Search    704

Difficulty:Easy

原题leetcode地址:  https://leetcode.com/problems/binary-search/

1.  二分法

时间复杂度:O(logn),一层while循环。

空间复杂度:O(n),没有申请ewai空间。

    /**
     * 二分法
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {

        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }

        int low = 0;
        int high = nums.length - 1;

        while (low <= high) {
            int mid = (low + high) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            else if (nums[mid] < target) {
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }

        return -1;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/86215700