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

34. 在排序数组中查找元素的第一个和最后一个位置 - 力扣(LeetCode)

思路:

使用两次二分查找,第一次找大于等于target的第一个位置,第二次找大于等于target + 1的第一个位置-1。

总结:

二分条件可以灵活地转换。

代码:

java 复制代码
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int n = nums.length;;
        int left = binary_search(nums, target);
        if(left == n || nums[left] != target) return new int[]{-1, -1};
        int right = binary_search(nums, target + 1);
        return new int[]{left, right - 1};
    }
    // >= 
    private int binary_search(int[] nums, int target) {
        int n = nums.length;
        int l = 0, r = n - 1;
        while(l <= r) {
            int mid = l + (r - l) / 2;
            if(nums[mid] < target) {
                l = mid + 1;
            }
            else {
                r = mid - 1;
            }
        }
        return l;
    }
}
相关推荐
JiaJZhong13 小时前
力扣.最长回文子串(c++)
java·c++·leetcode
凌肖战14 小时前
力扣网编程150题:加油站(贪心解法)
算法·leetcode·职场和发展
吃着火锅x唱着歌14 小时前
LeetCode 3306.元音辅音字符串计数2
算法·leetcode·c#
kngines14 小时前
【力扣(LeetCode)】数据挖掘面试题0003: 356. 直线镜像
leetcode·数据挖掘·直线镜像·对称轴
不見星空14 小时前
【leetcode】1751. 最多可以参加的会议数目 II
算法·leetcode
不見星空14 小时前
leetcode 每日一题 3439. 重新安排会议得到最多空余时间 I
算法·leetcode
SsummerC14 小时前
【leetcode100】下一个排列
python·算法·leetcode
shylyly_17 小时前
专题一_双指针_查找总价格为目标值的两个商品
c++·算法·leetcode·双指针·查找总价格为目标值的两个商品·和为s的两个数
嗜好ya18 小时前
LeetCode 560: 和为K的子数组
数据结构·算法·leetcode
myloveasuka20 小时前
leetcode11.盛最多水的容器
c语言·数据结构·c++·leetcode