[LeetCode]Sort Colors

来源:互联网 发布:mac屏幕截图保存位置 编辑:程序博客网 时间:2024/06/07 16:05

题目

Number: 75
Difficulty: Medium
Tags: Array, Two Pointers, Sort

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.

题解

排序颜色。假设有红白蓝三色,分别用0、1、2表示,三色顺序打乱,要按照同色相邻的原则排序,不同色按照红白蓝排序。

代码

void sortColors(vector<int>& nums) {    int i = 0, j = nums.size() - 1;    for(int k = 0; k <=j;){        if(nums[k] == 0)            swap(nums[k++], nums[i++]);        else if(nums[k] == 2)            swap(nums[k], nums[j--]);        else k++;    }}
0 0
原创粉丝点击