首页 > 代码库 > [leetcode]75.Sort Color三指针
[leetcode]75.Sort Color三指针
import java.util.Arrays; /** * 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. click to show follow up. Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0‘s, 1‘s, and 2‘s, then overwrite array with total number of 0‘s, then 1‘s and followed by 2‘s. Could you come up with an one-pass algorithm using only constant space? */ /* * 两种解法 * 1.三个指针:红指针,蓝指针,遍历指针(循环指针i),红蓝指针比别从前后端记录红色区域和蓝色区域的边界位置, * 遍历指针负责找到红蓝颜色的数据,白色的不用管,最后中间剩下的就是白色 * 2.记录红白蓝三色出现的次数,最后直接对数组进行相应的赋值 * 这里选用第一种 * 容易出错的地方:遍历指针和边界指针交换之后,还要在遍历指针的位置再判断一下是不是其他颜色, * 所以比较适合写成两个if分别判断,而且后边的if要加i--*/ public class Q75SortColors { public static void main(String[] args) { int[] nums = new int[]{2,2,2}; sortColors(nums); System.out.println(Arrays.toString(nums)); } public static void sortColors(int[] nums) { int red = 0; int blue = nums.length - 1; int temp; //获取红色区域的初始边界 for (int i =0;i < nums.length;i++) { if (nums[i] != 0) { red = i; break; } } //获取蓝色区域的初始边界 for (int i =nums.length-1;i >= 0 ;i--) { if (nums[i] != 2) { blue = i; break; } } //遍历交换归位 for (int i =red;i <= blue ;i++) { if (nums[i] == 0) { temp = nums[red]; nums[red] = nums[i]; nums[i] = temp; red++; } if (nums[i] == 2) { temp = nums[blue]; nums[blue] = nums[i]; nums[i] = temp; blue--; i--; } } } }
[leetcode]75.Sort Color三指针
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。