给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
import java.util.Scanner;
/**
* 给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
*
* @author Dell
*
*/
public class Test60 {
public static int searchInsert(int[] A, int target)
{
if(A.length==0)
return 0;
int index=-1;
for(int i=0;i<A.length;i++)
{
if(target>A[i])
continue;
else
{
index=i;
return index;
}
}
if(target>A[A.length-1])
return A.length;
return index;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
int target=sc.nextInt();
System.out.println(searchInsert(a,target));
}
}