LeetCode 704. Binary Search(二分查找)

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;
    }
发布了581 篇原创文章 · 获赞 97 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/104864340
今日推荐