75. Sort Colors--荷兰三色国旗问题
来源:互联网 发布:淘宝教学课程在哪里 编辑:程序博客网 时间:2024/05/01 06:11
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
【最简单:计数排序】
class Solution {public: void sortColors(int A[], int n) { int i = 0; int j = 0; int k = 0; for(int p = 0; p < n; p ++) { if(A[p] == 0) { i ++; } else if(A[p] == 1) { j ++; } else k ++; } for(int p = 0; p < n; p ++) { if(p < i) A[p] = 0; else if(p >= i && p < i + j) A[p] = 1; else A[p] = 2; } }};
【优化方法】采用三个变量,其中两个用来标记
如果只能扫一遍,很容易想到的就是左边存放0和1,右边存放2.两边往中间靠。
设置两个index,left记录第一个1的位置,left左边为0,right记录第一个非2的位置,right右边为2.
然后使用i从头到尾扫一遍,直到与right相遇。
i遇到0就换到左边去,遇到2就换到右边去,遇到1就跳过。
需要注意的是:由于left记录第一个1的位置,因此A[left]与A[i]交换后,A[left]为0,A[i]为1,因此i++;
而right记录第一个非2的位置,可能为0或1,因此A[right]与A[i]交换后,A[right]为2,A[i]为0或1,i不能前进,要后续判断。
由此该数组分为4段:[0,left)–>0; [left,i)–>1; [i,right]–>乱序; (right,n-1]–>2
0 0 0 1 1 1 2 1 0 2 1 2 2 2
^ ^ ^left i right
代码:不够优化
void swap(int *x,int *y) { int temp; temp = *x; *x = *y; *y = temp; } void sortColors(vector<int>& nums) { int len= nums.size(); int low = 0; int high = len-1; int index = 0; while(index <= high) { if(nums[index] == 0) { if(index != low) { swap(&nums[index],&nums[low]); low++; } else { index++; low++; } } else if(nums[index] == 2) { if(index != high) { swap(&nums[index],&nums[high]); high--; } else { index++; high--; } } else { index++; } } }
优化后:
class Solution {public: void sortColors(int A[], int n) { int left = 0; int right = n-1; int i = 0; while(i <= right) { if(A[i] == 0) { swap(A[left], A[i]); left ++; i ++; } else if(A[i] == 1) { i ++; } else { swap(A[i], A[right]); right --; } } }};
【最直观:平移插入】
class Solution {public: void sortColors(int A[], int n) { int i = -1; int j = -1; int k = -1; for(int p = 0; p < n; p ++) { //根据第i个数字,挪动0~i-1串。 if(A[p] == 0) { A[++k] = 2; //2往后挪 A[++j] = 1; //1往后挪 A[++i] = 0; //0往后挪 } else if(A[p] == 1) { A[++k] = 2; A[++j] = 1; } else A[++k] = 2; } }};
- 75. Sort Colors--荷兰三色国旗问题
- 【Sort】75. Sort Colors(计数排序、荷兰国旗问题)
- [LeetCode] 荷兰国旗问题 Sort Colors
- LeetCode | Sort Colors(荷兰国旗问题)
- 三色排序(荷兰国旗问题)
- 荷兰国旗问题,三色排序
- 【python】LeetCode | Sort Colors(荷兰国旗问题)
- 三色棋问题(荷兰国旗问题)
- 荷兰国旗-三色查找
- 荷兰国旗/三色排序
- 荷兰国旗问题 将3种数中重复数聚集 Sort Colors
- LeetCode(75)Sort Colors (荷兰三色旗问题 Dutch National Flag)
- 三色排序问题/(荷兰国旗问题)(C++版)
- Sort Colors(荷兰旗问题)
- 荷兰国旗问题
- 荷兰国旗问题
- 荷兰国旗问题
- 荷兰国旗问题
- code[vs]1026 逃跑的拉尔夫(bfs+判重)
- 一些编程中遇到的概念回顾
- java 基础学习------第四章数组的学习
- 搞定Gson泛型封装
- Linux操作系统安装ELK stack日志管理系统--(1)Logstash和Filebeat的安装与使用
- 75. Sort Colors--荷兰三色国旗问题
- 机器学习算法与Python实践之(二)支持向量机(SVM)初级
- 接口测试七(cache)
- iOS基础——通过案例学知识之xib、plist、mvc
- 6. GC 调优(工具篇)
- 如何使用HTML5新增标签(二)
- hdu1269 移动城堡 联通分量 Tarjan
- 深入解读Spring Framework Web MVC(第八弹:@SessionAttributes的使用)
- 什么是generic pointer(泛指针)