Leetcode(15)

来源:互联网 发布:淘宝推广电话 编辑:程序博客网 时间:2024/05/18 03:07

https://leetcode.com/problems/sort-colors/#/description

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.

Solution:

有趣的题,这道题我们记录rwb三种颜色的当前位置,遍历数组,然后根据情况在修改rwb位置的值,总共有三种情况:

1、当前位置为0,即要在r位置插入一个0,所以wb要后移,先在b的位置插入2,更新b,再在w的位置插入1,更新w,最后再对r进行操作。

2、当前位置为1,即要在w位置插入一个1,所以b要后移,先在b的位置插入2,更新b,再对r进行操作。

3、当前位置为2,即要在b位置插入一个2,更新b。

void SortColors::sortColors(vector<int> &nums) {    int r = 0, w = 0, b = 0;    for (int num : nums) {        switch (num){            case 0:                nums[b++] = 2;                nums[w++] = 1;                nums[r++] = 0;                break;            case 1:                nums[b++] = 2;                nums[w++] = 1;                break;            case 2:                nums[b++] = 2;                break;        }    }}

原创粉丝点击