LeetCode-M-Sort Colors

題意

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.

Difficulty: medium

解法

  • 各種排序算法
  • 利用兩個指針,一個指針指向1值的首元素,初始化爲數組頭節點,一個指針指向2值的首元素,初始化爲數據尾節點,另設一個指針遍歷數組元素

實現

class Solution {
public:
    void swapElements(vector<int>& nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    void sortColors(vector<int>& nums) {
        if(nums.size() <= 1) return;
        int p0 = 0;
        int cur = 0;
        int p2 = nums.size() - 1;
        while(cur <= p2){
            if(nums[cur] == 0){
                swapElements(nums,cur,p0);
                ++p0;
                ++cur;
            }else if(nums[cur] == 2){
                swapElements(nums,cur,p2);
                --p2;
            }else{
                ++cur;
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章