LeetCode:Sort Colors

来源:互联网 发布:侯振挺落选院士 知乎 编辑:程序博客网 时间:2024/06/05 09:38

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.

思路1:

  1. 题目和荷兰国旗问题是相同的
  2. 采用三个指针start,mid,end来操作,依据nums[mid]的值来判断下一步的操作
  3. 当nums[mid]=0时,swap(nums[start],nums[mid]),start++,mid++
  4. 当nums[mid]=1时,mid++
  5. 当nums[end]=2时,swap(num[end],nums[mid]) end–

思路2:

  1. 三指针赋值更新办法
    这种方法很巧妙,自己动手走一个例子,慢慢理解
#include "stdafx.h"#include "iostream"#include "vector"using namespace std;class Solution {public:    //方法2    void sortColors(vector<int>& nums)    {        int two = 0, one = 0, zero = 0;        for (int num : nums)        {            if (num == 2) { two++; }            if (num == 1) { nums[two++] = 2; nums[one++] = 1; }            if (num == 0) { nums[two++] = 2; nums[one++] = 1; nums[zero++] = 0; }        }    }    //方法1    void sortColor(vector<int>& nums) {        //the second solution        int start = 0, end = nums.size() - 1, mid=0,tmp;        while (mid <= end) {            if (nums[mid] == 0) {                //swap(nums[start++], nums[mid++]);                tmp = nums[start];                nums[start] = nums[mid];                nums[mid] = tmp;                mid++;                start++;            }            else if (nums[mid] == 1)            {                mid++;            }            else if (nums[mid] == 2) {                //swap(nums[mid], nums[end--]);                tmp = nums[end];                nums[end] = nums[mid];                nums[mid] = tmp;                end--;            }        }    }};int main(){    vector<int> nums;    nums.push_back(2);    nums.push_back(2);    nums.push_back(1);    nums.push_back(0);    nums.push_back(2);    Solution sol;    sol.sortColor(nums);    for (int i=0; i < nums.size(); i++)        cout << nums[i] << endl;    system("pause");    return 0;}
原创粉丝点击