Find the smallest number of K

Source: Internet
Author: User

Title Description

Enter n integers to output the smallest of the K.

Analysis and Solution method one

Requires a sequence of the smallest number of K, according to the usual way of thinking, it is first to the sequence from small to large, and then output the smallest number of k in front.

As for the sorting method of what to choose, I think you might think of the first time in a quick sort (we know that the average time for a fast sort n*logn ), and then traverse the sequence of the first k elements output. Therefore, the total time complexity: O(n * log n)+O(k)=O(n * log n) .

Solution Two

Let's consider further that the problem does not require the smallest number of k to be ordered, nor does it require the final n-k number to be ordered. In this case, it is not necessary to sort all the elements. At this time, we thought of the choice or exchange sort, namely:

1, traversing n number, the first to traverse to the number of k deposited into the size of the array of k, assuming that they are the smallest number of k;
2, to this k number, using the choice or exchange sorting to find the maximum value of this k element Kmax (find the maximum need to traverse this K number, time complexity is O(k) );
3, continue to traverse the remaining number of n-k. Assuming that the value of the new element to be traversed is X, compare X with Kmax: If x < kmax , replace Kmax with X, and go back to the second step to find the largest element in the array of k elements Kmax '; if x >= kmax , continue traversing does not update the array.

The time taken for each traversal, update, or not to update an array is O(k) either O(0) . So the whole trip down, the complexity of time n*O(k)=O(n*k) .

 void  Select_sortn (vector<int  > &vec, int   N) { int  size = Vec.size ();  for  (int  i = 0 ; I < n; ++i) {  I;  for  (int  j = i; j < size; ++J) { if  (vec[k] > Vec[j])            {k  = J;    }} swap (Vec[k], vec[i]); }}

Solution Three

A better approach is to maintain the largest heap of k, similar in principle to the method of solution two:

    • 1. The number of K that is first traversed by the largest heap with capacity K is also assumed to be the smallest number of k;
    • 2. The elements in the heap are ordered, so that K1<k2<...<kmax (Kmax is set to the largest element in the maximum heap)
    • 3. Traverse the number of remaining n-k. Suppose the value of the new element to be traversed is X, and the x is compared to the top element of the heap Kmax: If you x < kmax replace Kmax with X and then update the heap (spents logk), the heap is not updated.

So down, the total time complexity: O(k+(n-k)*logk)=O(n*logk) . This method is due to the time complexity of finding and updating in the heap: O(logk) (If you use solution two: Find the largest element in the array, time complexity: O(k)) .)

void heap_sortn (vector<int> &vec, vector<intint  n) {      for (int0; I! = N; + +i)    {        make_heap (Vec.begin (), Vec.end (), [] (intint j) {return i > j;});        res.push_back (*vec.begin ());        Vec.erase (Vec.begin ());}    }

Solution Four

In the "Data Structure and algorithm analysis--c language description", the 7th Chapter 7th. Section 7.6, the paper describes a fast selection algorithm with time complexity in the average case O(N) . As in the following text:

    • Select an element in S as the hub element V, divide the set s-{v} into S1 and S2, just like fast sorting
      • If k <= | s1|, then the smallest element of K must be in S1. In this case, return Quickselect (S1, K).
      • If k = 1 + | s1|, then the pivot element is the K-min element, which is found and returned directly.
      • Otherwise, the K-min element is in S2, which is the S2 (K-| s1| -1) Minimum element, we recursively call and return Quickselect (S2, K-| s1| -1).

The average run time for this algorithm is O (n).

This fast choice Select algorithm, similar to the fast sorting method. N number is stored in the array s, and then from the array to select "Median median" as the pivot element X, the array is divided into SA and Sb part, SA<=X<=SB, if the K element to find less than the number of elements of the SA, then return the SA smaller k elements, otherwise return all elements of the SA +SB Small and Medium k-| Sa| an element, the complexity that this solution can achieve on average O(n) .

Further, the 9th chapter of the Introduction to the algorithm, section 9.3, describes a select algorithm that has the worst case also O (n) time, which interested readers can refer to.

Extrapolate

1, Google interview questions: input is an array of two integers, they arbitrarily two number and can be composed of an array, to find this and the number of the first k how to do?

Analysis:

 “假设两个整数数组为A和B,各有N个元素,任意两个数的和组成的数组C有N^2个元素。   那么可以把这些和看成N个有序数列:          A[1]+B[1] <= A[1]+B[2] <= A[1]+B[3] <=…          A[2]+B[1] <= A[2]+B[2] <= A[2]+B[3] <=…          …         A[N]+B[1] <= A[N]+B[2] <= A[N]+B[3] <=…    问题转变成,在这N^2个有序数列里,找到前k小的元素”

2. There are two sequences A and b,a= (A1,A2,..., AK), b= (B1,B2,..., BK), and a and B are sorted in ascending order. For 1<=i,j<=k, ask for the smallest of K (AI+BJ). Requires the algorithm to be as efficient as possible.

3, given a sequence a1,a2,a3,..., an and M ternary group of queries, for each query (i,j,k), the output ai,ai+1,...,aj the number of ascending order K.

Find the smallest 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.