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.
package leetCode; import java.util.Arrays; /** * Created by lxw, liwei4939@126.com on 2018/3/11. */ public class L075_Sort_Colors { public void sortColors(int[] nums){ if (nums == null || nums.length == 0){ return; } int start = 0; int end = nums.length - 1; for (int i = start; i <= end; i++){ while (nums[i] == 2 && i < end){ swap(nums, i, end--); } while (nums[i] == 0 && i > start){ swap(nums, i, start++); } } } private void swap(int[] nums, int index1, int index2){ nums[index1] ^= nums[index2]; nums[index2] ^= nums[index1]; nums[index1] ^= nums[index2]; } public static void main(String[] args){ L075_Sort_Colors tmp = new L075_Sort_Colors(); int[] nums = new int[]{1, 1, 0, 2, 0, 1, 1, 2, 0}; tmp.sortColors(nums); System.out.println(Arrays.toString(nums)); } }
553




被折叠的 条评论
为什么被折叠?



