力扣labuladong一刷day8共2题

力扣labuladong一刷day8共2题

704. 二分查找

题目链接:https://leetcode.cn/problems/binary-search/
思路:很经典的题目,二分查找写的时候要注意循环不变量,如果是左闭右闭的话,那么leftright是有意义的,如果是左闭右开的话,leftright是无意义的。

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;
    }
}

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

题目链接:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
思路:寻找左边界与右边界,均使用二分查找来找,要注意的是相等时如何走,找左边界nums[mid]==target时,应该继续往左找,right=mid-1,同理右边界也是如此。

class Solution {
  public int[] searchRange(int[] nums, int target) {
        int left = getLeft(nums, target);
        int right = getRight(nums, target);
        return new int[]{left, right};
    }
    int getLeft(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 getRight(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,算法,数据结构,二分查找)