How to find the smallest Kth integer in an unsorted read-only array?

This is a standard question that has been answered many times on several sites, but there are additional restrictions in this version:

  • The array is read-only (we cannot modify the array).
  • Do it in O (1) space.

Can someone please explain to me the approach to this in the best possible time complexity.

+9
source share
2 answers

I am going to suggest that a read-only array is a strong requirement and is trying to find compromises that do not violate it in this answer (therefore, using selection, the algorithm is not an option since it modifies the array)

, wikipedia, O (1) :

, k + O (1) ( n - k, k > n/2), O (1) ....

O (k) O (nlogk). , k , O(1)

, heap k. k , . - x , x.

, - k th .


O O(n) O(k) space, 2k, , k th. , k'th, ( k). O(k*n/k) = O(n)

, , .


O (1) , , k . , . O(nk) O (1) , , , .

+11

O (n log d) O (1), . n , d - .

, k- . lo = hi = . , . Java :

    public int kthsmallest(final List<Integer> a, int k) {
        if(a == null || a.size() == 0)
             throw new IllegalArgumentException("Empty or null list.");
        int lo = Collections.min(a);
        int hi = Collections.max(a);

        while(lo <= hi) {
            int mid = lo + (hi - lo)/2;
            int countLess = 0, countEqual = 0;

            for(int i = 0; i < a.size(); i++) {
                if(a.get(i) < mid) {
                    countLess++;
                }else if(a.get(i) == mid) {
                    countEqual++;
                }
                if(countLess >= k) break;
            }

            if(countLess < k && countLess + countEqual >= k){
                return mid;
            }else if(countLess >= k) {
                hi = mid - 1;
            }else{
                lo = mid + 1;
            }
        }


        assert false : "k cannot be larger than the size of the list.";
        return -1;
    }

, / .

+22

All Articles