编写SearchInsertPosition类,实现查找和插入功能

 1 public class SearchInsertPosition {
 2     /*
 3      * 思路如下:
 4      * 1.先循环查找在数组中有没有一个数刚好等于目标数
 5      * 2.如果查找到了就直接返回数组下标
 6      * 3.如果查找不到的话,就再建立一个循环,查询目标数应该插入哪个位置合适
 7      * 如果目标数比数组的第一个数还小的话,就插入在最前面也就是数组下标为零的位置
 8      * 如果目标是比数组的最后一个数还大的话,就插入在最后面也就是数组下标为len的位置
 9      * 还有一种情况就是在两个数之间,要比较才能确定,
10      * 比较的条件为,应该比前面的数大,比后面的数小,插入的位置,就为后面的数的下标
11      * 
12      * 
13      * 
14      * */
15     public int searchInsert(int A[],int target)
16     {
17         int len=A.length;
18         boolean check=false;
19         for(int i=0;i<len;i++)
20         {
21             if(target==A[i])
22             {
23                 check=true;
24                 return i;
25             }            
26                 
27         }
28         if(!check)
29         {
30             for(int j=0;j<len;j++)
31             {
32                 if(target<=A[0])
33                 {
34                     
35                     return 0;
36 
37                 }
38                 else if(target>=A[len-1])
39                 {
40                     return len;
41                 }
42                 else if(target<=A[j]&&target>=A[j-1])
43                     return j;
44                 
45             }
46         }
47         
48         return 0;
49         
50     }
51 
52     public static void main(String[] args) {
53         // TODO Auto-generated method stub
54         int A[]={1,3,5,6};
55         SearchInsertPosition sip = new SearchInsertPosition();
56         int num = sip.searchInsert(A, 4);
57         System.out.println(num);
58     }
59 
60 }
原文地址:https://www.cnblogs.com/luoweiKnowledge/p/3959322.html