[LeetCode-Algorithms-75] "Sort Colors" (2017.12.7-WEEK14)

题目链接: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.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.


(1)思路:用三个指针,p1指向1元素的开始作为0和1的分界点;p2指向1元素的结尾作为1和2的分界点;p3用来遍历。如果p3指向的元素为0,那么交换p3和p1位置的元素。我们能够保证交换过来的元素是1,因此p1++,p3++;如果p3指向的元素是2,交换p2和p3指向的元素,p2–,p3不变。

(2)代码:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int n = nums.size();
        if (n == 0)  return;  
        int redIndex = 0;   
        int blueIndex = n - 1;  
        int index = 0;  
        while (index <= blueIndex)  
        {  
            if (nums[index] == 0)  
            {  
                swap(nums[index], nums[redIndex]);  
                redIndex++;  
                index++; 
            }  
            else if (nums[index] == 2)  
            {  
                swap(nums[index], nums[blueIndex]);  
                blueIndex--;  
            }  
            else  
                index++;  
        }  
    }
};

(3)提交结果:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_33454112/article/details/78744737