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;
    }
}
相关推荐
旖-旎9 小时前
LeetCode 279:完全平方数(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
良木林11 小时前
滑动窗口 - LeetCode hot 100
javascript·算法·leetcode·双指针·滑动窗口
晚笙coding12 小时前
LeetCode 108:将有序数组转换为二叉搜索树 —— 从数组到平衡二叉树的递归构造
数据结构·算法·leetcode
hold?fish:palm13 小时前
7 接雨水
开发语言·c++·leetcode
tkevinjd15 小时前
力扣148-排序链表
算法·leetcode·链表
wabs6661 天前
关于图论【力扣797.所有可能的路径的思考】
算法·leetcode·图论
Navigator_Z1 天前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
兰令水2 天前
hot100【acm版】【2026.7.19打卡-java版本】
java·数据结构·算法·leetcode·面试
tkevinjd2 天前
力扣72-编辑距离
算法·leetcode·职场和发展
什巳2 天前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode