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;
    }
}
相关推荐
Navigator_Z4 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木7 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.10 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.13 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用15 小时前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.15 小时前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi01116 小时前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b16 小时前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
0+1111 天前
算法 --模拟
c++·算法·leetcode
Nil2081 天前
leetcode 739每日温度
算法·leetcode·职场和发展