Leetcode: Sort Colors
来源:互联网 发布:jdk 7u80 linux x64 编辑:程序博客网 时间:2024/06/11 03:28
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.
比较直观的是快排,先移0,再移1.
class Solution {public: void sortColors(int A[], int n) { int i, j; for (i = 0, j = n - 1; i < j;) { while (i < j && A[i] == 0) { ++i; } while (i < j && A[j] != 0) { --j; } swap(A, i, j); } for (j = n - 1; i < j;) { while (i < j && A[i] == 1) { ++i; } while (i < j && A[j] != 1) { --j; } swap(A, i, j); } } void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }};要求只扫描一遍呢?可以设置两个变量,一个i表明1开始的位置,一个k表明2开始的位置。
class Solution {public: void sortColors(int A[], int n) { int i = 0, j = 0, k = n - 1; while (j <= k) { if (A[j] == 0) { swap(A, i++, j++); } else if (A[j] == 1) { j++; } else { swap(A, j, k--); } } } void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }};
======================第二次======================
class Solution {public: void sortColors(int A[], int n) { int i = 0; int j = 0; int k = n; while (j < k) { if (A[j] == 0) { swap(A, i++, j++); } else if (A[j] == 1) { ++j; } else { swap(A, j, --k); } } } void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }};
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- json换行替换及双引号替换
- Some Matrix manifolds (Lie group, Grassmann manifold and Riemannian manifold) for computer vision
- Hibernate工作原理及为什么要用?
- Msm7227-I2C设备驱动实现要点
- 层次聚类(1)
- Leetcode: Sort Colors
- android xbmc编译
- RTSP协议
- myeclipse 修改jsp模板
- Android对话框风格的窗口
- 零基础看图学GetPost模拟网页登录
- linux2.6.30内核中lcd驱动程序学习笔记3
- Error creating bean with name 'org.springframework.context.annotation.internalRequiredAnnotationProc
- 我使用过的Linux命令之trap - 在脚本中处理信号