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;
    }
}
相关推荐
java修仙传1 小时前
每日一题,力扣560. 和为 K 的子数组
算法·leetcode
ada7_1 小时前
LeetCode(python)——148.排序链表
python·算法·leetcode·链表
资深web全栈开发3 小时前
LeetCode 3625. 统计梯形的数目 II
算法·leetcode·组合数学
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——外观数列
算法·leetcode·职场和发展·结构与算法
Pluchon4 小时前
硅基计划4.0 算法 FloodFill算法
java·算法·leetcode·决策树·逻辑回归·深度优先·图搜索算法
Jac_kie_層樓6 小时前
力扣hot100刷题记录(12.2)
算法·leetcode·职场和发展
希望有朝一日能如愿以偿8 小时前
力扣每日一题:统计梯形的数目
算法·leetcode·职场和发展
jyyyx的算法博客10 小时前
LeetCode 面试题 16.22. 兰顿蚂蚁
算法·leetcode
Q741_14710 小时前
C++ 高精度计算的讲解 模拟 力扣67.二进制求和 题解 每日一题
c++·算法·leetcode·高精度·模拟
leoufung10 小时前
LeetCode 98 Validate Binary Search Tree 深度解析
算法·leetcode·职场和发展