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;
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章