leetcode 34. Find First and Last Position of Element in Sorted Array

33 篇文章 0 订阅
30 篇文章 0 订阅

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 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

tag:array, binary search

method 1

遍历数组,得到最小最大

method 2 binary search

首先,按照正常binary search首先在mid处找到一个target,因为数组已经排序好了,如果还有其他的target,那一定是在target的左边还有右边,如果有,那就分别以mid-1作为最右边界/mid+1作为最左边界继续查找,得到position更小/更大的数

public int[] searchRange(int[] nums, int target) {
    int first = Integer.MAX_VALUE, last = Integer.MIN_VALUE;
    int[] ans = searchRange(nums, target, 0, nums.length - 1,first,last);

    if (ans[0] == Integer.MAX_VALUE)
        return new int[]{-1,-1};
    return ans;
}

public int[] searchRange(int[] num, int target, int l, int r, int first, int last) {
    if (l > r) return new int[]{first, last};

    int mid = (l + r) / 2;
    if (num[mid] == target){
      first = Math.min(first,mid);
      last = Math.max(last,mid);
      int[] ans = new int[2];
      if (mid > 0 && num[mid-1] == target){
          ans = searchRange(num,target,l,mid-1,first,last);
          first = Math.min(first,ans[0]);
      }
      if (mid < num.length-1 && num[mid+1] == target){
          ans = searchRange(num,target,mid+1,r,first,last);
          last = Math.max(last,ans[1]);
      }
      return new int[]{first,last};
    } else if (num[mid] > target)
        return searchRange(num, target, l, mid-1, first, last);
    else return searchRange(num, target, mid+1, r, first, last);
}

summary

  1. 有序数组中查找数,很自然地就想到binary search
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值