https://leetcode.com/problems/sort-colors/description/

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int zero = 0, two = nums.size()-1;
       for(int index=0;index<=two;++index){
           if(nums[index]==0){
               swap(nums[zero++],nums[index]);
               //0和1的交换
           }else if(nums[index]==2){
               swap(nums[two--],nums[index--]);
//注意这里index--是为了平衡之后的index++从而让index不变,这是因为swap之后当前index位置上的元素被更新,需要重新检测一遍
                      }
       }

    }
};

results matching ""

    No results matching ""