- Find a sorted array elements in the first and last position
Nums Given an array of integers arranged in ascending order, according to the target and one target value. Identify a given target start and end positions in the array.
Your time complexity of the algorithm must be O (log n) level.
If the target is not present 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]
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
PS: Let me talk about a simple (using the powerful Java JDK)
class Solution {
public int[] searchRange(int[] nums, int target) {
int i = Arrays.binarySearch(nums, target);
if (i<0) return new int[]{-1,-1};
int begin = i;
int end = i;
while (begin-1>=0 && nums[begin-1]==target) {begin--;}
while (end+1<nums.length && nums[end+1]==target) {end++;}
return new int[]{begin,end};
}
}
PS: dichotomy
class Solution {
public int[] searchRange(int[] nums, int target) {
int i = 0, j = nums.length;
int mid = (i + j) / 2;
int p = -1;
while (i < j) { //找到target的位置
if (nums[mid] == target) {
p = mid;
break;
}
if (nums[mid] > target) {
if (j == mid) break;
j = mid;
mid = (i + j) / 2;
} else {
if (i == mid) break;
i = mid;
mid = (i + j) / 2;
}
}
if (p == -1) {
return new int[]{-1, -1};
} else { //在target所在位置向前向后查找
int a = p, b = p;
while (a > 0 && nums[a - 1] == target) a--;
while (b < nums.length - 1 && nums[b + 1] == target) b++;
return new int[]{a, b};
}
}
}