荷蘭國旗問題/三色旗問題(Leetcode 75. Sort Colors)
阿新 • • 發佈:2019-01-25
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.
class Solution { public: void sortColors(vector<int>& nums) { if(nums.empty()) return; int start = 0; int current = start; int end = nums.size()-1; while(current<=end) { if(nums[current] == 0) { if(nums[start]!=nums[current]) { int temp = nums[start]; nums[start] = 0 ; nums[current] = temp; } start++; current++; }else if(nums[current] == 1) { current++; }else{ if(nums[current]!=nums[end]) { int temp = nums[end]; nums[end] = 2; nums[current] = temp; } end --; } } return; } };