LeetCode (Sort Colors)

来源:互联网 发布:织梦 编辑器字体修改 编辑:程序博客网 时间:2024/04/26 10:11

Problem:

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.

Solution1:

class Solution {public:    void sortColors(vector<int>& nums) {        int i = 0, n = nums.size();        while(i < n){            if(nums[i] == 0){                nums.erase(nums.begin() + i);                nums.insert(nums.begin(), 0);                i++;            }else if(nums[i] == 1){                i++;            }else{                nums.erase(nums.begin() + i);                nums.push_back(2);                n--;            }        }    }};
Solution2:
class Solution {public:    void sortColors(vector<int>& nums) {        int n0 = 0, n = nums.size() - 1;        for(int i = 0; i <= n; i++){            if(nums[i] == 0)                swap(nums[i], nums[n0++]);            else if(nums[i] == 2)                swap(nums[i--], nums[n--]);        }    }};



0 0
原创粉丝点击