排序一个仅有3个唯一数字元素组成的列表

题目

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]
原文地址:https://www.cnblogs.com/new-start/p/11655199.html