玩命加载中 . . .

75-颜色分类


LeetCode 75. Sort Colors

LeetCode-75

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library’s sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

method

zero, one, two分别为0,1,2的末尾指针,遍历数组

  • 如果是0,则zero++, one++, two++
  • 如果是1,则one++, two++
  • 如果是2,则two++
void sortColors(vector<int>& nums) {
    int zero = -1;
    int one = -1;
    int two = -1;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == 0) {
            nums[++two] = 2;
            nums[++one] = 1;
            nums[++zero] = 0;
        }
        else if (nums[i] == 1) {
            nums[++two] = 2;
            nums[++one] = 1;
        }
        else {
            nums[++two] = 2;
        }
    }
}

two/one/zero指针移动的先后顺序不能修改,例如一开始的时候来个0,那如果zero先移动赋值,后面就会被onetwo覆盖了


文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录