LeetCode-M-Sort Colors
来源:互联网 发布:手机淘宝会员怎么注册 编辑:程序博客网 时间:2024/05/29 19:20
题意
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.
Difficulty: medium
解法
- 各种排序算法
- 利用两个指针,一个指针指向1值的首元素,初始化为数组头节点,一个指针指向2值的首元素,初始化为数据尾节点,另设一个指针遍历数组元素
实现
class Solution {public: void swapElements(vector<int>& nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } void sortColors(vector<int>& nums) { if(nums.size() <= 1) return; int p0 = 0; int cur = 0; int p2 = nums.size() - 1; while(cur <= p2){ if(nums[cur] == 0){ swapElements(nums,cur,p0); ++p0; ++cur; }else if(nums[cur] == 2){ swapElements(nums,cur,p2); --p2; }else{ ++cur; } } }};
0 0
- LeetCode-M-Sort Colors
- 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
- tcp基本套接字编程函数
- 欢迎使用CSDN-markdown编辑器
- 如何将本地项目上传到GitHub
- java多线程:3、线程互斥
- K-diff Pairs in an Array
- LeetCode-M-Sort Colors
- 【p1032-子串变换】解题记录
- mysql导入大量数据
- 淘宝atlas框架初探atlas-core(二):Bundle插件化
- Week Training: 513 Find Bottom Left Tree Value
- Ubuntu安装aspect
- Tensorflow学习笔记--模型保存与调取
- 十进制转任意进制
- 数据格式