力扣labuladong——一刷day09

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣704. 二分查找
  • 二、力扣34. 在排序数组中查找元素的第一个和最后一个位置


前言


一、力扣704. 二分查找

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){
                right = mid - 1;
            }else{
                left = mid + 1;
            }
        }
        return -1;
    }
}

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

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[2];
        int left = 0, right = nums.length -1, mid;
        while(left <= right){
            mid = left + (right-left)/2;
            if(nums[mid] == target){
                right = mid - 1;
            }else if(nums[mid] > target){
                right = mid -1;
            }else{
                left = mid + 1;
            }
        }
        if(left >= nums.length){
            res[0] = -1;
        }else{
            res[0] = nums[left] == target ? left : -1;
        }

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

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