Find the x smallest integers in a list of length n

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

    What about using a splay tree? Because of the splay tree's unique approach to adaptive balancing it makes for a slick implementation of the algorithm with the added benefit of being able to enumerate the x items in order afterwards. Here is some psuedocode.

    public SplayTree GetSmallest(int[] array, int x)
    {
      var tree = new SplayTree();
      for (int i = 0; i < array.Length; i++)
      {
        int max = tree.GetLargest();
        if (array[i] < max || tree.Count < x)
        {
          if (tree.Count >= x)
          {
            tree.Remove(max);
          }
          tree.Add(array[i]);
        }
      }
      return tree;
    }
    

    The GetLargest and Remove operations have an amortized complexity of O(log(n)), but because the last accessed item bubbles to the top it would normally be O(1). So the space complexity is O(x) and the runtime complexity is O(n*log(x)). If the array happens to already be ordered then this algorithm would acheive its best case complexity of O(n) with either an ascending or descending ordered array. However, a very odd or peculiar ordering could result in a O(n^2) complexity. Can you guess how the array would have to be ordered for that to happen?

提交回复
热议问题