Sword Point of Offer (Java Edition): Minimum number of K

Source: Internet
Author: User

Title: Enter n integers to find the smallest number of K. For example, enter 4,5,1,6,2,7,3,8 these 8 numbers, then the smallest 4 numbers are 1,2,3,4

The simplest way of thinking about this problem is to sort the n integers in the input, and the number of K in the first place after sorting is the smallest number of K. The time complexity of this idea is O (Nlogn), and the interviewer will prompt us for a faster algorithm.

Solution One: O (n) algorithm, only if we suspect modifying the input array is available

From the previous question we can be inspired, we can also be based on the partition function to solve the problem. If you adjust based on the K number of the array so that all numbers smaller than the K number are on the left side of the array, all numbers larger than the K number are on the right side of the array. After this adjustment, the K number in the left side of the array is the smallest K number. Here is the Java code based on this idea:

/** * Enter n integers to find the smallest of the k integers, and find the smallest number of K. * For example, enter 4,5,1,6,2,7,3,8 these 8 numbers, then the smallest 4 digits are 1,2,3,4 */package swordforoffer;/** * @author Jinshuangqi * * August 8, 2015 */PUBL  IC class E30kleastnumbers {//use partition function public int partition (int[] arr, int left, int right) {int result = Arr[left];if (Left > right) return-1;while (left < right) {while (left < right && Arr[right] >= result) {right--;} Arr[left] = Arr[right];while (Left < right && Arr[left] < result) {left++;} Arr[right] = Arr[left];} Arr[left] = Result;return left;}  Public int[] Getleastnumbers (int[] Input,int k) {if (Input.length = = 0 | | k<= 0) return null;int[] output = new Int[k];int Start = 0;int End = Input.length-1;int index = partition (Input,start,end), while (Index! = k-1) {if (Index > k-1) {end = in Dex-1;index = partition (Input,start, end);} Else{start = Index+1;index = partition (Input,start, end);}} for (int i = 0;i<k;i++) {Output[i] = input[i];} return output;} public static void Main (string[] args) {int[] arr= {4,5,1,6,2,7,3,8}; E30kleastnumbers test = new E30kleastnumbers (); int[] Output=test.getleastnumbers (arr, 4); for (int i = 0;i< Output.length; i++) {System.out.print (output[i]+ ",");}}}
There is a limit to adopting this approach. We need to modify the input array, because the function partition adjusts the order of the numbers in the array. What do we do if the interviewer asks that the input array cannot be modified?

Solution Two: O (NLOGK) algorithm, particularly suitable for processing large amounts of data

We can first create a data container of size k to store the smallest number of k, and then each time we read a number from the input n integers. If there are already fewer than k numbers in the container, put the integer read into the container directly, and if the container already has a K number, that is, the container is full, at this point we can no longer insert a new number and can only replace the existing number. Find the maximum value in the existing K number and compare it with the integer and maximum value that you want to insert. If the value to be inserted is smaller than the current minimum value, replace the current maximum value with this number, and if the value to be inserted is greater than the current maximum, then this number cannot be one of the smallest k integers, so we can discard the integer.

So when the container is full, we have to do 3 things, one is to find the largest number in K integers, and the other is the possibility to delete the maximum number in this container; third, it is possible to insert a new number. If you use a binary tree to implement this container, then we can achieve these three steps in O (LOGK) time. Therefore, for the number of n inputs, the total time efficiency is O (NLOGK).

We can choose to implement this data container with a different two-fork tree. Since we need to find the largest number of k integers every time, we can easily think of using the largest heap. In the maximum heap, the value of the root node is always greater than the value of any node in its subtree. So every time we suspect in O (1) We get the maximum value of the K number, but we need O (LOGK) time to complete the delete and insert operation.

Here is the Java code implementation steps:

/** * Enter n integers to find the smallest of the k integers, and find the smallest number of K. * For example, enter 4,5,1,6,2,7,3,8 8 numbers, then the smallest 4 digits are 1,2,3,4 */package swordforoffer;import java.util.arrays;/** * @author Jinshuangqi * * August 8, 2015 */public class E30kleastnumbers {//New large top heap public void Buildmaxheap (int[] Arr,int lastIndex) {for (int i = (lastIndex-1)/2;i>=0;i--) {int k = i;while (2*k+1 <= lastIndex) {int biggerindex = 2*k+1;if (Biggerindex < LastIndex) {if (arr[biggerindex]< arr[biggerindex+1]) biggerindex++;} if (Arr[k] < Arr[biggerindex]) {swap (arr,k,biggerindex); k = Biggerindex;} Elsebreak;}}} public static void Swap (int[] arr,int i, int j) {int temp = Arr[i];arr[i] = arr[j];arr[j] = temp;} public void Heapsort (int[] arr) {for (int i = 0;i<arr.length-1;i++) {buildmaxheap (arr,arr.length-i-1); Swap (arr,0, arr.length-i-1);}} public void Getleastnumbers (int[] Arr,int k) {if (arr = = NULL | | k<0 | | k>arr.length) return;//based on input array before k number of resumes Max//from k + 1 number starts with root node comparison//greater than root node, DE//less than, replace root node, rebuild Max heap int[] Karray = Arrays.copyofrange (arr, 0, k); Heapsort (Karray); for (int i = k;i<arr.length;i++) {if (arr[i]<karray[k-1]) {karray[k-1] = Arr[i];heapsort (Karray);}} for (int i:karray) System.out.print (i);} public static void Main (string[] args) {int[] arr= {4,5,1,6,2,7,3,8}; E30kleastnumbers test = new E30kleastnumbers (); Test.getleastnumbers (arr, 3);}}
Solution Comparison:

The average time complexity of the first solution based on the function partition is O (n), which is faster than the second, but it also has obvious limitations, such as modifying the input array.

The second solution, though slower, has two distinct advantages. One is that the input data is not modified. Second, the algorithm is suitable for large amounts of data input (including Baidu and many companies are very fond of large data-related problems). If the topic is to ask for the smallest number of k numbers from a large amount of data, because the size of the memory is limited, it may not be able to load these massive data into memory all at once. At this time, we can assist storage space (such as disk) to read a number each time, according to Getleastnumbers way to determine whether it is necessary to put the container leastnumbers. This approach only requires memory to accommodate leastnumbers. So it fits the case that n is big and K is small.

For example, compare two algorithms:

Since each of these two algorithms have advantages and disadvantages, each applicable to different occasions, so the candidate before writing code to understand the requirements of the topic, including the amount of input data, can be loaded into memory, whether to allow the exchange of input data in the order of the numbers.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Sword Point of Offer (Java Edition): Minimum number of K

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.