Find the x smallest integers in a list of length n

前端 未结 12 1751
时光取名叫无心
时光取名叫无心 2021-02-02 01:00

You have a list of n integers and you want the x smallest. For example,

x_smallest([1, 2, 5, 4, 3], 3) should return [1, 2, 3].

I\'ll v

相关标签:
12条回答
  • 2021-02-02 01:25
    sort array
    slice array 0 x
    

    Choose the best sort algorithm and you're done: http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms

    0 讨论(0)
  • 2021-02-02 01:27

    You can sort then take the first x values?

    Java: with QuickSort O(n log n)

    import java.util.Arrays;
    import java.util.Random;
    
    public class Main {
    
        public static void main(String[] args) {
            Random random = new Random(); // Random number generator
            int[] list = new int[1000];
            int lenght = 3;
    
            // Initialize array with positive random values
            for (int i = 0; i < list.length; i++) {
                list[i] = Math.abs(random.nextInt());
            }
    
            // Solution
            int[] output = findSmallest(list, lenght);
    
            // Display Results
            for(int x : output)
                System.out.println(x);
        }
    
        private static int[] findSmallest(int[] list, int lenght) {
            // A tuned quicksort
            Arrays.sort(list);
            // Send back correct lenght
            return Arrays.copyOf(list, lenght);     
        }
    
    }
    

    Its pretty fast.

    0 讨论(0)
  • 2021-02-02 01:31

    In scala, and probably other functional languages, a no brainer:

    scala> List (1, 3, 6, 4, 5, 1, 2, 9, 4)  sortWith ( _<_ ) take 5
    res18: List[Int] = List(1, 1, 2, 3, 4)
    
    0 讨论(0)
  • 2021-02-02 01:32

    In pseudo code:

    y = length of list / 2
    
    if (x > y)
      iterate and pop off the (length - x) largest
    else
      iterate and pop off the x smallest
    

    O(n/2 * x) ?

    0 讨论(0)
  • 2021-02-02 01:34

    Add all n numbers to a heap and delete x of them. Complexity is O((n + x) log n). Since x is obviously less than n, it's O(n log n).

    0 讨论(0)
  • 2021-02-02 01:35

    Maintain the list of the x highest so far in sorted order in a skip-list. Iterate through the array. For each element, find where it would be inserted in the skip list (log x time). If in the interior of the list, it is one of the smallest x so far, so insert it and remove the element at the end of the list. Otherwise do nothing.

    Time O(n*log(x))

    Alternative implementation: maintain the collection of x highest so far in a max-heap, compare each new element with top element of the heap, and pop + insert new element only if the new element is less than the top element. Since comparison to top element is O(1) and pop/insert O(log x), this is also O(nlog(x))

    0 讨论(0)
提交回复
热议问题