首页 > 代码库 > two pointers类型笔记整理

two pointers类型笔记整理

对撞型指针

1. sort colors

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.

 

因为只有3个颜色需要排序,可以用2根指针遍历一遍数组。更general的做法为counting/bucket sort。

技术分享
 1 public class Solution { 2     public void sortColors(int[] nums) { 3         int red = 0, current = 0, blue = nums.length - 1; 4         while (current <= blue) { 5             if (nums[current] == 0) { 6                 swap(red, current, nums); 7                 red++; 8                 current++; 9             } else if (nums[current] == 2) {10                 swap(current, blue, nums);11                 blue--;12             } else {13                 current++;14             }15         }16         17         18         19     }20     private static void swap(int i, int j, int[] nums) {21         int temp = nums[i];22         nums[i] = nums[j];23         nums[j] = temp;24     }25 }
sort colors

 

two pointers类型笔记整理