75. Sort Colors
阿新 • • 發佈:2021-12-06
Given an array nums 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.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Example 3:
Input: nums = [0]
Output: [0]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
n == nums.length
1 <= n <= 300
nums[i] is 0, 1, or 2.
Follow up:Could you come up with a one-pass algorithm using onlyconstant extra space?
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/sort-colors
class Solution { // 優化,只遍歷一次 public void sortColors(int[] nums) { int left = 0, right = nums.length - 1; int i = left; while (i <= right) { // 2歸位,right指標左移 if (nums[i] == 2) { swap(nums, i, right--); } else if (nums[i] == 0) { // 0放到最左邊 swap(nums, i++, left++); } else { i++; } } } /** 本質考察快速排序思想 兩次遍歷:第一次遍歷先將0歸位,第二次遍歷將1歸位,自然2也就歸位了 */ public void sortColors1(int[] nums) { int pos = 0; // 將0歸位 for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { swap(nums, i, pos); pos++; } } // 將1歸位 for (int j = pos; j < nums.length; j++) { if (nums[j] == 1) { swap(nums, j, pos); pos++; } } } private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }