LeetCode 34. Find First and Last Position of Element in Sorted Array
原题链接在这里:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
题目:
Given an array of integers 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
题解:
是Search Insert Position的变形,就是找边界情况。
只需要做两遍Binary Search.
第一遍用来找左边界,若是取mid小于target, 左边界会在后半部分. 若mid 大于 或者 等于 target时左边界都会在前半部分。
第二遍用来找右边界,原理相同。
然后如何判断是否找到过target呢,若是找到了target, 那么ll 不会在rr 的右侧,若是如此更改res结果,否则直接返回res.
Time Complexity: O(logn). Space: O(1).
1 public class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 //Method 2 4 int [] res = {-1,-1}; 5 if(nums == null || nums.length == 0){ 6 return res; 7 } 8 //find left bound 9 int ll = 0; 10 int lr = nums.length - 1; 11 while(ll<=lr){ 12 int mid = ll+(lr-ll)/2; 13 if(nums[mid] < target){ 14 ll = mid+1; 15 }else{ 16 lr = mid-1; 17 } 18 } 19 //find right bound 20 int rl = 0; 21 int rr = nums.length - 1; 22 while(rl<=rr){ 23 int mid = rl+(rr-rl)/2; 24 if(nums[mid] <= target){ 25 rl = mid+1; 26 }else{ 27 rr = mid-1; 28 } 29 } 30 //check if target is found 31 if(ll>rr){ 32 return res; 33 } 34 res[0] = ll; 35 res[1] = rr; 36 return res; 37 } 38 }