题目
Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
Challenge: Try sorting the list using constant space.
分析
遍历一遍,计数每个唯一元素出现的次数。然后根据计数生成排序好的结果数组。
时间复杂度 O(n).
代码
def sortNums(nums):
# count
counts = [0, 0, 0]
for n in nums:
counts[n - 1] += 1
# sort
return [1] * counts[0] + [2] * counts[1] + [3] * counts[2]
print sortNums([3, 3, 2, 1, 3, 2, 1])
# [1, 1, 2, 2, 3, 3, 3]