美文网首页
Sort Colors (Leetcode 75)

Sort Colors (Leetcode 75)

作者: stepsma | 来源:发表于2016-11-13 13:54 被阅读0次

这题考查 Three-Way Partition 要点是while loop条件是有等于号的

while(start <= right)

同时,了解一下Rainbow Sort的算法。

void sortColors(vector<int> &nums) {
        // write your code here
        if(nums.empty()) return;
        int left = 0, right = nums.size()-1;
        int start = 0;
        while(start <= right){
            if(nums[start] == 0){
                swap(nums[left], nums[start]);
                left++; start++;
            }else if(nums[start] == 2){
                swap(nums[start], nums[right]);
                right--;
            }else{
                start++;
            }
        }
    }

相关文章

网友评论

      本文标题:Sort Colors (Leetcode 75)

      本文链接:https://www.haomeiwen.com/subject/axdcpttx.html