The main point of the topic is the combination of array and sequencing, the following straight to the point:
Topic Description: Enter n integers to find the smallest number of K. For example, enter the 4,5,1,6,2,7,3,8 of these 8 digits, then the smallest 4 digits are 1,2,3,4.
Title Requirements: Time limit: 1 seconds space limit: 32768K
To solve the problem : first, after seeing the problem, we have to find the smallest number of k in the array, we have to compare the length of K and the group, only the length of the array is greater than K, we can return this number of K. Then, how do we accept the number of K returned? We're going to define an array that has a length of K. Once the preparations are in place, we will begin to think about how to find the smallest number of K. We will certainly say sort of without hesitation. Yes, that's sort of, what sort of order can improve efficiency. We can't sort all the arrays, then take the smallest number of k, which will greatly reduce the efficiency, because we have to order the number of the back (ARRAY.LENGTH-K) is redundant, so we just have to do the K-order array to get the smallest number of K. Here I'm using a sort of selection instead of bubbling because the bubble sort takes a data exchange every time, and it's too time-consuming to select a sort that only needs to define a variable to point to the smallest value and then swap it with the previous one.
Code implementation:
public class Test03 {public int[] solution (int [] input, int k) {//This is the relationship to check k,input.length and their values, if they do not meet the requirements Returns null if (K<1| | input.length<1| |
INPUT.LENGTH<K) {return null;
}//define a length of k array, data storage int[] Dest = new Int[k]; The following is the Select sort//Just get the first k of the array, all we have to do is loop K for (int i = 0; i < K; i++) {//define a TEMP variable
, equivalent to pointer int temp = i; Each time you iterate from the first I, temp points to the smallest number for (int j = i+1 J < Input.length; J + +) {if (input[temp)
>INPUT[J]) {temp = J;
(=///The value pointed to by temp is exchanged with input[i] int s = input[i];
Input[i] = input[temp];
Input[temp] = s;
Assigning the value of Input[i] to dest[i] dest[i] = input[i];
return dest;
public static void Main (string[] args) { Test03 test = new Test03 ();
Int[] array = {3,4,2,8,5,6,1,7,9};
int[] Dest = test.solution (array, 5);
System.out.print ("Operation result:");
for (int i:dest) {System.out.print (i+ ""); }
}
}
Run Result:
Summary
This topic mainly examines the idea that the array is sorted, there are several common sorts, such as bubble sort, select sort, fast sort, hill sort, etc., these sorts I will explain in the Java data structure, hope everybody pays attention to. In addition, the efficiency of the algorithm determines the ability of programmers, we should not only focus on running results do not pay attention to the efficiency of the algorithm.