Find the x smallest integers in a list of length n

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

        private static int[] x_smallest(int[] input, int x)
        {
            int[] output = new int[x];
            for (int i = 0; i < x; i++) { // O(x)
                output[i] = input[i];
            }
    
            for (int i = x; i < input.Length; i++) { // + O(n-x)
                int current = input[i];
                int temp;
    
                for (int j = 0; j < output.Length; j++) { // * O(x)
                    if (current < output[j]) {
                        temp = output[j];
                        output[j] = current;
                        current = temp;
                    } 
                }
            }
    
            return output;
        }
    

    Looking at the complexity: O(x + (n-x) * x) -- assuming x is some constant, O(n)

提交回复
热议问题