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;
    }
}
相关推荐
旖旎夜光5 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊5 小时前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt5 小时前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊5 小时前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent6 小时前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
Pniubi8 小时前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
j7~1 天前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing1 天前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊1 天前
LeetCode1261~1280题目解析
java·leetcode
Shaoshing1 天前
LeetCode100 11. 盛最多水的容器
算法·leetcode