您的位置:首页 > 其它

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)。

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]);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: