[Algorithm-Java implementation] Find the start and end positions of elements in the sorted array
1. Problem description:
1. Input: Input an integer array arr that has been arranged in ascending order and a target value target.
2. Output: output the start position and end position index of the target value target in the array. If target does not exist in the array, it returns [-1,-1].
3. For example: input {5,7,7,8,8,10}, target=8; output [3,4]
Input {5,7,7,8,8,10}, target=6; output [-1,-1]
Input {5,7,7,8,8,810}, target=8; output [3,5]
Input {5,7,7,8,8,8,10}, target=10; output [6,6]
Input {5,7,7,8,8,8,10}, target=5; output [0,-1]
2. Question answer:
method: Linear scan (i.e. traverse the array in turn )
The first traverse traverses from left to right until the index value of the starting position is found; the second traversal traverses from right to left until the index value of the end position is found.
3. Algorithm analysis:
1. The time complexity is O(N), and the extra space complexity is O(1).
code show as below
import java.util.Arrays;
import java.util.Scanner;
/*
* 问题:在排序数组中查找元素的开始位置和结束位置
*/
public class SearchRange {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
String str=in.nextLine();
int target=in.nextInt();
String [] strArray=str.split(",");
int[] arr=new int[strArray.length];
for(int i=0;i<arr.length;i++) {
arr[i]=Integer.valueOf(strArray[i]);
}
int[] result= SearchRange(arr, target);
System.out.println(Arrays.toString(result));
}
public static int [] SearchRange(int []arr,int target) {
int[] result= {
-1,-1};
for(int i=0;i<arr.length;i++) {
if(arr[i]==target) {
result[0]=i;
break;
}
}
if(result[0]==-1) {
return result;
}
for(int j=arr.length-1;j>0;j--) {
if(arr[j]==target) {
result[1]=j;
break;
}
}
return result;
}
}