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]spa
Challenge: Try sorting the list using constant space.code
遍歷一遍,計數每一個惟一元素出現的次數。而後根據計數生成排序好的結果數組。
時間複雜度 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]