package LeetCode.contact;
import java.util.Arrays;
//在排序数组中查找元素的第一个和最后一个位置
class Solution_34 {
public int[] searchRange(int[] nums, int target) {
//使用二分查找寻找到和target一样的数值,并返回它的位置
int temp = Arrays.binarySearch(nums, target);
int temp_r = temp;
int temp_l = temp;
// System.out.println(temp);
//如果不存在这样的数,则返回[-1,-1]
if(temp <0 ){
int []arr = new int[]{-1,-1};
return arr;
}
//统计temp左右各有多少相同的数
int left = 0;
int right = 0;
//如果存在这样的数,搜索他的左右是否也存在相同的数
if(temp >= 0 ){
while(temp_r < nums.length-1 && nums[temp_r+1] == target){
right++;
temp_r++;
}
while(0<temp_l && nums[temp_l-1] == target){
left++;
temp_l--;
}
}
// System.out.println("right:" + right);
// System.out.println("left:" + left);
//返回数组a
int[] a = new int[2];
a[0] = temp - left;
a[1] = temp + right;
return a;
}
}
public class leetcode_34 {
public static void main(String[] args){
int[] nums = new int[]{2,2};
int target = 2;
Solution_34 test = new Solution_34();
int[] pp = test.searchRange(nums, target);
System.out.println(Arrays.toString(pp));
}
}
LeetCode_34:在排序数组中查找元素的第一个和最后一个位置:Java
最新推荐文章于 2023-12-17 19:07:58 发布