zoukankan      html  css  js  c++  java
  • two pointers类型笔记整理

    目录:

    1. 一个数组从两边往中间移动(对撞型)

    2. 一个数组同时向前移动(前向型)

    3. 两个数组(并行型)

    1. 对撞型/相会型指针

    1. two sum, three sum, 4 sum, k sum 类  

    2.灌水类问题

    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
  • 相关阅读:
    nginx开启ssl模式
    安装nginx
    node的express框架
    使用Thumbnails工具对图片进行缩放,压缩
    正则
    VUE设置全局方法和属性
    js——XHR知识归纳
    页面资源加载过程
    Mongodb的增删改查
    Mongodb基本概念
  • 原文地址:https://www.cnblogs.com/jiangchen/p/5918526.html
Copyright © 2011-2022 走看看