计蒜客 挑战难题 寻找插入位置

给定一个已经升序排好序的数组,以及一个数 targettargettarget,如果 targettargettarget 在数组中,返回它在数组中的位置。

否则,返回 targettargettarget 插入数组后它应该在的位置。

假设数组中没有重复的数。以下是简单的示例:

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

输入格式

第一行输入一个整数 nnn。

第二行输入 nnn 个整数,表示数组A[n]

第三行输入 targettargettarget。

输出格式

输出一行,为要求返回的结果。

样例输入

3
1 3 5
2

样例输出

1

=========================
第一次code:

 1 import java.util.*; 
 2 
 3 public class Main
 4 {  
 5     public static void main(String[] args)
 6     {
 7         Scanner input = new Scanner(System.in);
 8         int n = input.nextInt();
 9         int [] array = new int[n];
10         for(int i=0;i<n;i++)
11         {
12             array[i]=input.nextInt();
13         }
14         int target = input.nextInt();
15         System.out.println(run(n,array,target));
16     }
17     public static int run(int n,int []a,int target)
18     {
19         int c=0;
20         for(int i=0;i<n;i++)
21         {
22             if(a[i]==target)
23             {
24                 c=i;
25             }
26             else
27             {
28                 if(a[i]>target)
29                 {
30                     c=i;
31                     break;
32                 }
33                 else
34                 {
35                     c=n;
36                 }
37             }
38         }
39         return c;
40     }
41 }
 
原文地址:https://www.cnblogs.com/niithub/p/5799447.html