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]
思路:题目要求时间复杂度为O(log n),且数组有序,可用二分查找法。但数组中有重复的元素,因此需要对二分查找作一点修改。
代码:
//二分查找 -- 有重复元素 查找最开头与最结尾的目标值 public static int[] searchRange(int[] nums, int target) { int[] res = new int[2]; List<Integer> l = new ArrayList<>(); int left = 0; int right = nums.length-1; while(left<=right){ int mid = (left+right)/2; if(nums[mid]==target){ int start = mid; int end = mid; //获取start的索引 while(start>=0){ if(nums[start]!=target){ break; } start--; } l.add(start+1); //获取end的索引 while(end<=nums.length-1){ if(nums[end]!=target){ break; } end++; } l.add(end-1); break; }else if(nums[mid]<target){ left = mid+1; }else{ right = mid-1; } } if(l.size()==0){ res[0] = -1; res[1] = -1; }else{ res[0] = l.get(0); res[1] = l.get(1); } return res; }
当然,如果不考虑时间复杂度,也可用暴力法。
代码:
//暴力循环 public static int[] searchRange(int[] nums, int target) { int[] res = new int[2]; List l = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if(nums[i] == target){ l.add(i); } } if(l.size()==0){ res[0] = res[1] =-1; }else if(l.size()==1){ res[0] = res[1] = (int) l.get(0); }else{ res[0] = (int) l.get(0); res[1] = (int) l.get(l.size()-1); } return res; }