34. Find First and Last Position of Element in Sorted Array
一、题目
1、审题
2、分析
求 target 在有序数组 nums 中出现的最小下标和最大下标组成的数组。否则返回 {-1, -1}。时间复杂度为 O(log n)。
二、解答
1、思路:
时间复杂度为 O(log n),想到用二分法。要求所在下标组合,则需在求得 target时在向前、向后查找 target,直至找到 target 出现的最大、最小下标。
class Solution { public int[] searchRange(int[] nums, int target) { int len = nums.length; int[] result = new int[]{-1, -1}; int low = 0; int high = len - 1; if(len == 0) return result; if(target < nums[low] || target > nums[high]) return result; while(low < high) { int median = (low + high) / 2; if(nums[median] > target) high = median - 1; else if(nums[median] < target) low = median + 1; else { low = median; high = median; while(low - 1 >= 0 && nums[low - 1] == target) low--; while(high + 1 < len && nums[high + 1] == target) high++; break; } } if(nums[low] == target) { result[0] = low; result[1] = high; } return result; } }