Solution 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.
classSolution{ publicvoidsortColors(int[] nums){ int p2 = nums.length-1; int p1=0; int p0=0; while (p1<=p2){ if (nums[p1] == 0){ int tmp = nums[p0]; nums[p0] = nums[p1]; nums[p1] = tmp; p0++; p1++; }elseif(nums[p1] == 2){ int tmp = nums[p2]; nums[p2] = nums[p1]; nums[p1] = tmp; p2--; }else{ p1++; } } } }
Python代码
第一种
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defsortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums); for i in range (-1,n): for j in range (i+1, n): if(nums[i]>nums[j]): tmp = nums[i]; nums[i] = nums[j]; nums[j] = tm