鼓楼区建设房产和交通局网站,手机上怎么自己做网站,做淘宝客网站详细步骤,企业网站整理优化34.在排序数组中查找元素的第一个和最后一个位置
给你一个按照非递减顺序排列的整数数组 nums#xff0c;和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target#xff0c;返回 [-1, -1]。
你必须设计并实现时间复杂度为…34.在排序数组中查找元素的第一个和最后一个位置
给你一个按照非递减顺序排列的整数数组 nums和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target返回 [-1, -1]。
你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
示例 1
输入nums [5,7,7,8,8,10], target 8
输出[3,4]示例 2
输入nums [5,7,7,8,8,10], target 6
输出[-1,-1]示例 3
输入nums [], target 0
输出[-1,-1]提示
0 nums.length 105-109 nums[i] 109nums 是一个非递减数组-109 target 109 该题考察的是二分法二分法求左右边界问题 //荷兰国旗问题两次二分
public class Problem_0034_FindFirstAndLastPositionOfElementInSortedArray {public static int[] searchRange(int[] nums, int target) {int[] ans { -1, -1 };if (nums null || nums.length 0) {return ans;}ans[0] findFirst(nums, target);ans[1] findLast(nums, target);return ans;}public static int findFirst(int[] arr, int num) {int L 0;int R arr.length - 1;int ans -1;int mid 0;while (L R) {mid L ((R - L) 1);if (arr[mid] num) {L mid 1;} else if (arr[mid] num) {R mid - 1;} else {ans mid;// 此处因为要找的target最左边界所有移动R为mid - 1再看左边还有没有target值R mid - 1;}}return ans;}public static int findLast(int[] arr, int num) {int L 0;int R arr.length - 1;int ans -1;int mid 0;while (L R) {mid L ((R - L) 1);if (arr[mid] num) {L mid 1;} else if (arr[mid] num) {R mid - 1;} else {ans mid;// 此处因为要找的target最右边界所有移动L为mid 1再看右边还有没有target值L mid 1;}}return ans;}
}