Leetcode 34. Find First and Last Position of Element in Sorted Array [medium][java]

本文探讨了在已排序的整数数组中查找特定目标值的起始和结束位置的两种算法。第一种方法采用线性扫描,时间复杂度为O(n),第二种方法使用二分搜索,时间复杂度降低至O(log n)。通过具体实例和代码实现,展示了如何高效地解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example
在这里插入图片描述

Solution 1: linear scan
Consideration

  1. start from the beginning, find the leftmost index of the target
  2. Then start from the end, find the rightmost index.

Time Complexity: O(n), space complexity: O(1)

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        //find the leftmost index
        for(int i=0; i < nums.length; i++) {
            if(nums[i] == target) {
                res[0] = i;
                break;
            } else if(nums[i] > target) {
                break;
            }
        }
        //not found
        if(res[0] == -1)
            return res;
        
        for(int i = nums.length-1; i>=res[0]; i--) {
            if(nums[i] == target) {
                res[1] = i;
                break;
            }
        }
        
        return res;
        
    }
    

}

Solution 2: Binary search
Time Complexity: O(log (n)), space complexity: O(1)

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = {-1, -1};
    int leftIndex = indexSearch(nums, target, true);
    // 表示未找到target
    if (leftIndex == nums.length || nums[leftIndex] != target) {
        return result;
    }

    result[0] = leftIndex;
    // 因为返回的是最右位置的下一个位置,需要进行减 1 操作
    result[1] = indexSearch(nums, target, false) - 1;
    return result;
    }
    
    private int indexSearch(int[] nums, int target, boolean isLeft) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target && isLeft) { // 如果是查最左位置,则应继续在左半部分查找,否则在右半部分查找
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
    

}

References
1.https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/

  1. https://blog.youkuaiyun.com/xiaoguaihai/article/details/85030318
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值