Find First and Last Position of Element in Sorted Array
阿新 • • 發佈:2018-12-25
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]
思路:就是binary search,一個search左邊一個search 右邊;注意邊界情況,一次完成,開心!
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1,-1}; if(nums == null || nums.length == 0) return res; res[0] = findleft(nums, target, 0, nums.length-1, true); res[1] = findleft(nums, target, 0, nums.length-1, false); return res; } public int findleft(int[] nums, int target, int start, int end, boolean findleft){ if(start > end){ return -1; } else { int mid = start+(end-start)/2; if(findleft){ if(nums[mid] == target){ if((mid-1>=0 && nums[mid-1] != target) || mid == 0){ return mid; } else { return findleft(nums, target, start, mid-1, findleft); } } else if(nums[mid] > target){ return findleft(nums, target, start, mid-1, findleft); } else { // nums[mid] < target; return findleft(nums, target, mid+1, end, findleft); } } else { // find right index; if(nums[mid] == target){ if((mid+1<=nums.length-1 && nums[mid+1] != target) || mid == nums.length-1){ return mid; } else { return findleft(nums, target, mid+1, end, findleft); } } else if(nums[mid] > target){ return findleft(nums, target, start, mid-1, findleft); } else { // nums[mid] < target; return findleft(nums, target, mid+1, end, findleft); } } } } }