Sort Colors - LeetCode
2015-10-24 10:18
281 查看
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.
思路:使用两个int变量,这里我命名为left和right (或slow和fast)。这两个变量其实相当于两个指针,初始时都为0,即指向nums数组中下标为0的数。
之后,right负责向右扫描一次nums数组。这次扫描的目的是把数组中所有的0都移到数组前端。
具体扫描的规则是,right从0开始,判断当前下标中的数是否为0,若是则与left所指向位置的数交换,然后left加一;若不为0,则跳过这个数。
经过一次循环后,我们再将所有的1都移到0后面。注意,经过前一次扫描后,left所指的下标正好是数组里所有0后面的第一个位置。
此时令right=left,继续扫描,扫描规则和上次类似,不过这次是判断是否为1。扫描结束后算法结束,所有的2也已自动到了数组的最右。
整个算法的时间复杂度为O(n),空间复杂度为O(1)。
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.
思路:使用两个int变量,这里我命名为left和right (或slow和fast)。这两个变量其实相当于两个指针,初始时都为0,即指向nums数组中下标为0的数。
之后,right负责向右扫描一次nums数组。这次扫描的目的是把数组中所有的0都移到数组前端。
具体扫描的规则是,right从0开始,判断当前下标中的数是否为0,若是则与left所指向位置的数交换,然后left加一;若不为0,则跳过这个数。
经过一次循环后,我们再将所有的1都移到0后面。注意,经过前一次扫描后,left所指的下标正好是数组里所有0后面的第一个位置。
此时令right=left,继续扫描,扫描规则和上次类似,不过这次是判断是否为1。扫描结束后算法结束,所有的2也已自动到了数组的最右。
整个算法的时间复杂度为O(n),空间复杂度为O(1)。
class Solution { public: void sortColors(vector<int>& nums) { int n = nums.size(); if (n < 2) return; int left = 0, right = 0; for (; right < n; right++) { if (nums[right] > 0) continue; swap(nums[left++], nums[right]); } for (right = left; right < n; right++) { if (nums[right] > 1) continue; swap(nums[left++], nums[right]); } } };
相关文章推荐
- 项目目标文档
- vs2010 打开的项目关闭后不显示
- ubuntu10.04 编译 Android工程
- hdu1196 Lowest Bit
- Xcode 升级后, 插件无法使用的问题( PluginLoading: Required plug-in compatibility UUID.... )
- 查看、关闭某一runlevel下自动启动的服务
- 51nod 1079 中国剩余定理 (模板)
- 简单管理心得
- 九度OJ 1123:采药 (01背包、DP、DFS)
- 九度OJ 1123:采药 (01背包、DP、DFS)
- Leetcode Minimum Size Subarray Sum
- Eclipse4.4.1安装velocity插件Veloeclipse.ui_2.0.8
- 【CUDA并行程序设计系列(1)】GPU技术简介
- 在 Linux 下使用 RAID(九):如何使用 ‘Mdadm’ 工具管理软件 RAID
- 在 Linux 下使用 RAID(九):如何使用 ‘Mdadm’ 工具管理软件 RAID
- table超长部分用...代替
- Hyper-v 虚拟机安装win7
- Hyper-v 虚拟机安装win7
- 教你快速高效接入SDK——总体思路和架构
- 二叉树最大宽度(递归方式和非递归方式)