首页 > 其他 > 详细

two pointers类型笔记整理

时间:2016-09-29 07:42:36      阅读:210      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!