Write the searchinsertposition class to implement the search and insert functions.

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.