LeetCode Sort Colors

1.题目

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.

2.解决方案

class Solution {public:void sortColors(int A[], int n) {int left = 0;int right = n – 1;int current = 0;while(current <= right){if(A[current] == 0){swap(A[left], A[current]);++left;++current;}else if(A[current] == 2){swap(A[current], A[right]);–right;}else{++current;}}}};

思路:首先题目的意思把一个只有0,,1,2的乱序数组排序成000111222的次序。因为只有3个数,所以可以用3个变量来交换,把0都换到前面,把2都换到后面。用一个指向开头,用一个指向结尾,把2都换到尾部去。

自己不喜欢的人,可以报之以沉默微笑;

LeetCode Sort Colors

相关文章:

你感兴趣的文章:

标签云: