Here is another way, which assumes that all numbers in the range 1,...,k appear (as per the problem description):
def inOrder(nums):
k = max(nums)
indices = [nums.index(n) for n in range(1,k+1)]
return [n for i,n in sorted(zip(indices,range(1,k+1)))]
For example
>>> inOrder([4, 2, 1, 1, 2, 1, 1, 3, 2])
[4, 2, 1, 3]
It is O(nk)
where n
is the length of the list. On the other hand, it uses built-in methods which are fairly quick, and if on average the first appearance of each number is somewhat early in the list, then the runtime will be much better than the worst-case. For example, if you define:
nums = [random.randint(1,1000) for i in range(10**6)]
then the evaluation of inOrder(nums)
takes less than a second (even though the list has 1 million entries).