1. 程式人生 > >LeetCode 75. Sort Colors (顏色排序)

LeetCode 75. Sort Colors (顏色排序)

原題

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library’s sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.
  • Could you come up with a one-pass algorithm using only constant space?

Reference Answer

思路分析

這道題本身不難,難點在要求一次遍歷完成排序。

這道題不允許使用排序庫函式。那麼最直觀的解法是:遍歷兩遍陣列,第一遍對0,1,2計數,第二遍對陣列進行賦值,這樣是可以ac的。但題目的要求是隻使用常數空間,而且只能遍歷一遍。那麼思路就比較巧妙了。設定兩個頭尾指標,頭指標p0指向的位置是0該放置的位置,尾指標p2指向的位置是2該放置的位置。i用來遍歷整個陣列,碰到0把它和p0指向的數交換,碰到2把它和p2指向的數交換,碰到1繼續向後遍歷。有點類似快速排序的分割陣列這一步。

class Solution:
    def sortColors
(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # if not nums: # return [] # temp_list = [1 for i in range(len(nums))] # min_index = 0 # max_index = len(nums) - 1 # for x in nums: # if x == 0: # temp_list[min_index] = 0 # min_index += 1 # if x == 2: # temp_list[max_index] = 2 # max_index -= 1 # for index in range(len(nums)): # nums[index] = temp_list[index] if not nums: return [] start_index = 0 end_index = len(nums) - 1 index = 0 while index <= end_index: if nums[index] == 2: nums[end_index], nums[index] = nums[index], nums[end_index] end_index -= 1 elif nums[index] == 0: nums[start_index], nums[index] = nums[index], nums[start_index] start_index += 1 index += 1 else: index += 1

Note:

  • 本題在所含元素已知的前提下,完成一次遍歷排序的思想很值得借鑑,即設定頭指標p1,尾指標p2,i用來遍歷整個陣列,碰到0把它和p1指向的數交換,碰到2把它和p2指向的數交換,碰到1繼續向後遍歷。有點類似快速排序的分割陣列這一步。