two pointers类型笔记整理
Posted 毛线刷题笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了two pointers类型笔记整理相关的知识,希望对你有一定的参考价值。
目录:
1. 一个数组从两边往中间移动(对撞型)
2. 一个数组同时向前移动(前向型)
3. 两个数组(并行型)
1. 对撞型/相会型指针
1. two sum, three sum, 4 sum, k sum 类
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 }
以上是关于two pointers类型笔记整理的主要内容,如果未能解决你的问题,请参考以下文章