LeetCode-M-Sort Colors

来源:互联网 发布:手机淘宝会员怎么注册 编辑:程序博客网 时间:2024/05/29 19:20

题意

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;            }        }    }};
0 0
原创粉丝点击