欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 704. Binary Search(二分查找)

程序员文章站 2024-01-04 15:50:16
...
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.


Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

You may assume that all elements in nums are unique.
有序数组中无重复元素

   public int search(int[] nums, int target) {
        //搜索区间为左闭右闭:[left, right]
        int left = 0, right = nums.length - 1;

        //当搜索区间为空时,跳出循环
        while(left <= right) {
            int mid = left + (right - left) / 2;

            if(nums[mid] == target) {
                return mid;
            }
            else if(nums[mid] < target) {
                left = mid + 1;
            }
            else if(nums[mid] > target) {
                right = mid - 1;
            }
        }
        
        return -1;
    }

上一篇:

下一篇: