[Leetcode] 75. 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.

Language: C++

解法一:
基本思想:计数排序(适用于元素种类很有限的情况)
思路:只用记录数组中0,1,2分别出现的次数,然后再把它们依次放回数组中就好了。
Time: O(n) O ( n )
Space: O(1) O ( 1 )
遍历了好几遍

class Solution {
public:
    void sortColors(vector<int>& nums) {

        int count[3] = {0}; //存放0,1,2三个元素的频率
        for(int i = 0; i < nums.size(); i++){
            assert(nums[i] >= 0 && nums[i] <= 2);
            count[nums[i]] ++;//在这道题中,这里不会出现数组越界
        }
        int index = 0;//来跟踪放回数组时的位置
        for(int i = 0; i < count[0]; i++)
            nums[index++] = 0;
        for(int i = 0; i < count[1]; i++)
            nums[index++] = 1;
        for(int i = 0; i < count[2]; i++)
            nums[index++] = 2;

    }
};

算法细节:

  • 在做和数组相关的问题时,一旦在方括号中取值,就要小心数组越界的问题。(在做与链表相关的问题时,一旦要访问结点的元素,如node->value中node结点的value时,就要考虑这个结点不能为空!)
  • 依次循环放入的部分是较为繁琐的,如何优化来简化放入过程,使得即使是0~100也可以使用这个思路。

解法二:
基本思想:使用三路快排partition
思路:用三个指针zero,i,two来控制。zero保证从[0…zero]的元素都等于0; two保证从[two…n-1]的元素都等于2,i是遍历指针。
T
如果当前元素等于0,则和nums[zero+1]的元素进行交换,同时zero++,且i也要加1(因为当i!=zero+1时,即i>zero+1时,zero+1的位置上一定是1;当i=zero+1时,比如数组第一个元素就是0的情况,此时swap它自己,然后zero++和i++,也没有问题);如果当前元素等于2,则two–,再让nums[2]和当前元素交换,此时i不能动,因为新交换的这个元素还没有比较过;如果当前元素就是1,直接i++就可以了。
Time: O(n) O ( n )
Space: O(1) O ( 1 )
只遍历了一遍

class Solution {
public:
    void sortColors(vector<int>& nums) {

        int zero = -1; //nums[0...zero] == 0
        int two = n; //nums[two...n-1] == 2
        for(int i = 0; i < two;){
            if( nums[i] == 1)
                i++;
            else if(nums[i] == 2)
                swap(nums[i], nums[++two]);
            else{//nums[i]==0
                assert( num[i] == 0);
                swap(nums[++zero],nums[i++]);          
            }
        }     
    }
};

算法细节:

  • for循环的条件是i < two而不是i <= two因为two已经保证[two,n-1]范围内都是2,所以不考虑等于的情况。
  • for循环中没有i++,因为有一种情况是不需要i++的,所以空在那里就好了。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值