博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode:Sort Colors (面试 笔试)
阅读量:7078 次
发布时间:2019-06-28

本文共 1664 字,大约阅读时间需要 5 分钟。

Question:

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.

Note:

You are not suppose to use the library's sort function for this problem.

Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

问题:给定一个长度为n的数组,里边有red,white,blue这些颜色,把他们进行排序,以便让他们相邻的元素毗邻,顺序为red,white,blue,在这里,用0,1,2分别代表red,white,和blue三种颜色。不能使用排序的类库,要求在O(N)时间复杂度,O(1)的空间复杂度完成排序。

思路:借鉴快速排序的思想,或者《剑指Offer》中的一个题(对于一个数组,把奇数放在偶数前面)的思想,设置两个指针,一个从前向后扫描(i),一个从后向前扫描(j),i指向的数如果等于0,则继续往后,知道它指向的不为0,对于j指向的数不等于0继续往前,直到等于0,这样在第一个循环完成,0已经排好序,下面再对1和2排序,同样的道理。具体看下边代码:

1 void swap(int &a, int&b) 2 { 3     int temp = a; 4     a = b; 5     b = temp; 6 } 7 void sortColors(int A[], int n)  8 { 9     int i = 0;10     int j = n - 1;11     int k = n - 1;12     int count = 0;13     for (int i = 0; i < n;i++)14     if (A[i] == 0)15         count++;//求出0的个数16     while (i < j){
//循环完成后,0已经就位17 while (i < j&&A[i] == 0) i++;18 while (i < j&&A[j] != 0)j--;19 swap(A[i++], A[j--]);20 }21 i = count;22 while (i < k){
//循环完成 1已经就位 相应2也应该就位23 while (i < k&&A[i] == 1)i++;24 while (i < k&&A[k] != 1)k--;25 swap(A[i++], A[k--]);26 }27 }

 

转载于:https://www.cnblogs.com/zhaolizhen/p/SortColors.html

你可能感兴趣的文章
lsattr, chattr
查看>>
redis key设置过期时间
查看>>
0514JS基础:操作document对象、事件、this
查看>>
Gtest:源码解析
查看>>
【杂题总汇】HDU2018多校赛第九场 Rikka with Nash Equilibrium
查看>>
获取FIle路径下所有文件的地址和名称
查看>>
11.HTML表单元素【中】
查看>>
浙大版《C语言程序设计(第3版)》题目集 练习3-4 统计字符 (15 分)
查看>>
oracle创建计划任务
查看>>
16进制转10进制
查看>>
windows 安装服务
查看>>
MySQL常用简单小命令
查看>>
ERROR: child process failed, exited with error number 100 mongodb报错
查看>>
epoll 使用小结
查看>>
c#调用存储过程实现登录界面
查看>>
测试类。。。重写篇
查看>>
二进制
查看>>
入侵式与非入侵式JavaScript
查看>>
ny47 过河问题
查看>>
神奇高效的Linux命令行
查看>>