Find the x smallest integers in a list of length n

前端 未结 12 1760
时光取名叫无心
时光取名叫无心 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: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.

提交回复
热议问题