【LeetCode】90. Sort Colors
阿新 • • 發佈:2018-12-14
題目描述(Medium)
Given an array 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.
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.
題目連結
Example 1:
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
演算法分析
由於只有三種顏色,可以設定兩個index,一個是red的index,一個是blue的index,兩邊往中間走。
提交程式碼:
class Solution { public: void sortColors(vector<int>& nums) { int red = 0, blue = nums.size() - 1; for (int i = 0; i < blue + 1; ) { if (nums[i] == 0) swap(nums[i++], nums[red++]); else if (nums[i] == 2) swap(nums[i], nums[blue--]); else ++i; } } };