力扣labuladong一刷day22天二分搜索共2题

力扣labuladong一刷day22天二分搜索共2题

一、704. 二分查找

题目链接:https://leetcode.cn/problems/binary-search/
思路:典型的二分查找,如果是左闭右闭那么说明left <= right 。如果左闭右开那么说明 left < right

class Solution {
   public int search(int[] nums, int target) {
        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 {
                right = mid - 1;
            }
        }
        return -1;
    }
}

二、34. 在排序数组中查找元素的第一个和最后一个位置

题目链接:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
思路:分别寻找左右边界。

class Solution {
  public int[] searchRange(int[] nums, int target) {
        int left = findLeft(nums, target);
        int right = findRight(nums, target);
        return new int[]{left, right};
    }

    int findLeft(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid-1;
            }else {
                left = mid+1;
            }
        }
        if (left < 0 || left >= nums.length) return -1;
        return nums[left] == target ? left : -1;
    }

    int findRight(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] <= target) {
                left = mid+1;
            }else {
                right = mid-1;
            }
        }
        if (right < 0 || right >= nums.length) return -1;
        return nums[right] == target ? right : -1;
    }
}

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