class Solution { public: void sortColors(vector<int>& nums) { sort(nums.begin(), nums.end()); } };
上面这个太弱了,给一个强不了多少的
1 class Solution: 2 def sortColors(self, nums: 'List[int]') -> 'None': 3 red = 0 4 white = 0 5 blue = 0 6 for n in nums: 7 if n == 0: 8 red+=1 9 elif n == 1: 10 white += 1 11 elif n == 2: 12 blue += 1 13 else: 14 print('error') 15 nums.clear() 16 nums.extend([0]*red + [1]*white + [2]*blue)
下面给出一个比较强的
1 class Solution: 2 def swap(self,nums,i,j): 3 nums[i],nums[j] = nums[j],nums[i] 4 ''' 5 temp = nums[i] 6 nums[i] = nums[j] 7 nums[j] = temp 8 ''' 9 10 def sortColors(self, nums: 'List[int]') -> 'None': 11 n = len(nums) 12 left = 0 13 right = n - 1 14 i = 0 15 while i <= right: 16 if nums[i] == 0: 17 if i != left: 18 self.swap(nums,i,left) 19 i += 1 20 left += 1 21 elif nums[i] == 1: 22 i += 1 23 else: 24 self.swap(nums,i,right)
注意swap的写法,如果用temp来存,速度会慢很多。