1 public class searchinsertposition {2/* 3 * the idea is as follows: 4*1. first, cyclically query whether there is a number in the array that is exactly equal to the number of targets 5*2. if the search result is found, the array subscript 6*3 is returned. if you cannot find the target, create a loop and insert the target number to a proper position. 7 * If the target number is smaller than the first number of the array, insert at the beginning, that is, the position where the array subscript is zero. 8 * if the target is larger than the last number of arrays, insert it to the end, that is, the position where the array subscript is Len. 9 * another case is that the comparison can be determined between two numbers. The condition of 10 * comparison is, it should be larger than the preceding number, smaller than the following number, and the Insert Location, it is the subscript of the following number 11*12*13*14 */15 public int searchinsert (int A [], int target) 16 {17 int Len =. length; 18 Boole An 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 stub54 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}
Write the searchinsertposition class to implement the search and insert functions.