做网站 转行,语言可以做网站吗,wordpress的站点地址如何配置,标书制作的六步骤需求 思路 使用二分查找找到第一个值#xff0c;以第一个值作为界限#xff0c;分为左右两个区间在左右两个区间分别使用二分查找找左边的7,#xff1a;找到中间位置的7之后#xff0c;将中间位置的7作为结束位置#xff0c;依次循环查找#xff0c;知道startend,返回…需求 思路 使用二分查找找到第一个值以第一个值作为界限分为左右两个区间在左右两个区间分别使用二分查找找左边的7,找到中间位置的7之后将中间位置的7作为结束位置依次循环查找知道startend,返回start这就是7第一次出现的位置找右边的7,找到中间位置的7之后将中间位置的7作为开始位置依次循环查找知道startend,返回end这就是7最后一次出现的位置 代码 左边索引 private static int getLeftIndex(int[] nums, int target) {int start 0;int end nums.length - 1;while (start end) {int mid start (end - start) / 2;if (nums[mid] target) {end mid - 1;} else if (nums[mid] target) {start mid 1;} else {end mid - 1;}}if (start nums.length || nums[start] ! target) {return -1;}return start;
}右边索引 private static int getRightIndex(int[] nums, int target) {int start 0;int end nums.length - 1;while (start end) {int mid start (end - start) / 2;if (nums[mid] target) {start mid 1;} else if (nums[mid] target) {start mid 1;} else {end mid - 1;}}if (end 0 || nums[end] ! target) {return -1;}return end;
}main函数 返回 leftIndex 3 rightIndex 5 int[] nums {1,3,3,7,7,7,8,8,9};
int target 7;
int leftIndex getLeftIndex(nums, target);
int rightIndex getRightIndex(nums, target);
System.out.println(leftIndex leftIndex);
System.out.println(rightIndex rightIndex);