【面试题 & LeetCode 75】 Sort Colors

题目描述

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?

思路

第一种是计数三个元素分别的个数,最后一个for循环覆盖原先的数组。
第二种是两个值维护0和2的位置,遍历数组,如果是0,往左边移动,如果是2,往右边移动。

代码

计数:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int cnt1 = 0, cnt2 = 0, cnt3 = 0;
        int n = nums.size();
        for (int i=0; i<n; ++i) {
            if (nums[i] == 0) cnt1++;
            else if (nums[i] == 1) cnt2++;
            else cnt3++;
        }
        
        int cnt = 0;
        while(cnt < n) {
            if (cnt1 > 0) {
                cnt1--;
                nums[cnt++] = 0;
            }
            else if (cnt2 > 0) {
                cnt2--;
                nums[cnt++] = 1;
            }else {
                cnt3--;
                nums[cnt++] = 2;
            }
        }
    }
};

双指针:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int n = nums.size();
        int l = 0, r = n-1;
        
        for (int i=0; i<n; ++i) {
            if (i == r+1) break;
            if (nums[i] == 0) {
                swap(nums[l++], nums[i]);
            }else if (nums[i] == 2) {
                swap(nums[r--], nums[i]);
                i--;
            }
        }
        
        return;
    }
};
发布了340 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105629552