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;
    }
}
相关推荐
无敌最俊朗@1 小时前
力扣hot100-206反转链表
算法·leetcode·链表
Kuo-Teng1 小时前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
CoderYanger2 小时前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节
前进的李工4 小时前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
吃着火锅x唱着歌6 小时前
LeetCode 面试题 16.24.数对和
算法·leetcode·职场和发展
Dream it possible!6 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
Wenhao.6 小时前
LeetCode Hot100 每日温度
数据结构·算法·leetcode·golang
吃着火锅x唱着歌6 小时前
LeetCode 1679.K和数对的最大数目
算法·leetcode·职场和发展
im_AMBER6 小时前
Leetcode 57
笔记·学习·算法·leetcode
im_AMBER6 小时前
Leetcode 58 | 附:滑动窗口题单
笔记·学习·算法·leetcode