subject
Given an ascending array of integers, nums, and a target value, target. Find the start and end position of the given target value in the array.
Your algorithm time complexity must be O(log n) level.
Returns [- 1, - 1] if the target value does not exist in the array.
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]
Thinking of problem solving dichotomy: the time complexity of problem searching must be O(log n), so dichotomy must be adopted for this problem. There are two ways to write:
- When the middle value of binary search = target, search from the middle value to both sides to get the boundary.
- When the middle value of binary search = target, continue binary search in the left and right half of the array to find the boundary.
Java problem solving search to both sides
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1, -1}; if(nums==null || nums.length==0) return res; int tar = beamSearch(nums, 0, nums.length-1, target); if(tar==-1) return res; int left = tar, right = tar; while(left-1>=0 && nums[left-1]==target) left--; while(right+1<nums.length && nums[right+1]==target) right++; res[0] = left; res[1] = right; return res; } public int beamSearch(int[] nums, int left, int right, int target){ if(left>right) return -1; int mid = left + (right-left)/2; if(nums[mid]==target){ return mid; }else if(nums[mid]<target){ return beamSearch(nums, mid+1, right, target); }else return beamSearch(nums, left, mid-1, target); } }
Java problem solving - two binary searches
class Solution { public int[] searchRange(int[] nums, int target) { int[] pos = new int[]{Integer.MAX_VALUE,Integer.MIN_VALUE}; beamSearch(nums,target,0,nums.length-1,pos); if(pos[0]==Integer.MAX_VALUE) return new int[]{-1,-1}; else return pos; } public void beamSearch(int[] nums,int target,int low,int high,int[] pos){ if(low>high) return; int mid=low+(high-low)/2; if(nums[mid]==target){ if(mid<pos[0]) pos[0]=mid; if(mid>pos[1]) pos[1]=mid; beamSearch(nums,target,low,mid-1,pos); beamSearch(nums,target,mid+1,high,pos); }else if(nums[mid]>target) beamSearch(nums,target,low,mid-1,pos); else beamSearch(nums,target,mid+1,high,pos); } }