description: Given an array with n objects colored red, white or blue, sort them 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.
可以使用雙指針的算法來進行計算,但是這用因為程序就只有3個變量,因此可以使用特定的判斷來進行運算。
public class Solution { public void sortColors(int[] nums) { if (nums == null || nums.length < 1) { return; } int left = 0; int right = nums.length - 1; int i = 0; while (i <= right) { if (nums[i] == 0) { swap(nums, left, i); left++; i++; } else if (nums[i] == 1) { i++; } else { swap(nums, i, right); right--; } } } private void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; }}新聞熱點
疑難解答