码迷,mamicode.com
首页 > 其他好文 > 详细

two pointers类型笔记整理

时间:2016-09-29 07:44:20      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

对撞型指针

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类型笔记整理

标签:

原文地址:http://www.cnblogs.com/jiangchen/p/5918526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!