Leetcode(15)
来源:互联网 发布:淘宝推广电话 编辑:程序博客网 时间:2024/05/18 03:07
https://leetcode.com/problems/sort-colors/#/description
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.
有趣的题,这道题我们记录rwb三种颜色的当前位置,遍历数组,然后根据情况在修改rwb位置的值,总共有三种情况:
1、当前位置为0,即要在r位置插入一个0,所以wb要后移,先在b的位置插入2,更新b,再在w的位置插入1,更新w,最后再对r进行操作。
2、当前位置为1,即要在w位置插入一个1,所以b要后移,先在b的位置插入2,更新b,再对r进行操作。
3、当前位置为2,即要在b位置插入一个2,更新b。
void SortColors::sortColors(vector<int> &nums) { int r = 0, w = 0, b = 0; for (int num : nums) { switch (num){ case 0: nums[b++] = 2; nums[w++] = 1; nums[r++] = 0; break; case 1: nums[b++] = 2; nums[w++] = 1; break; case 2: nums[b++] = 2; break; } }}
阅读全文
0 0
- leetcode-15
- Leetcode 15
- LeetCode 15
- Leetcode(15)
- leetcode 15
- LeetCode 15
- Leetcode 15 3Sum
- LeetCode 15: 3Sum
- leetcode 15 3Sum
- [leetcode 15] 3Sum
- Leetcode【15】:3Sum
- [leetcode 15] 3Sum
- [Leetcode] 15 - 3Sum
- leetcode.15-----------3Sum
- leetcode 15 3Sum
- leetcode-15 3Sum
- 3Sum - LeetCode 15
- Leetcode #15 3 Sum
- 我维护过的三套SAP双机总结
- USACO-Section1.3 Ski Course Design
- K-means算法、EM算法——斯坦福CS229机器学习个人总结(五)
- mysql编码问题
- 网页爬虫-R语言实现基本函数
- Leetcode(15)
- Linux压缩归档
- Django06模型(Model)
- 字符串替换
- Scala-基础语法
- QT面试题
- Echarts绘制横向柱状图(圆角+渐变)
- FFT,快速傅里叶变换学习笔记
- Are virtual interfaces supported on Quagga v0.98.3 (on Debian GNU/Linux 2.6.16)?