Skip to content

Latest commit

 

History

History
39 lines (32 loc) · 895 Bytes

sort-colors.md

File metadata and controls

39 lines (32 loc) · 895 Bytes

Solution

    class Solution {
    public:
        void swap(vector<int>& nums, int i, int j ) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
        void sortColors(vector<int>& nums) {
            int lo = 0, hi = nums.size() - 1;
            int mid = 0;
            while(mid <= hi) {
                if(nums[mid] == 0) {
                    swap(nums, lo, mid);
                    lo++;
                    mid++;
                }
                else if(nums[mid] == 2) {
                    swap(nums, hi, mid);
                    hi--;
                }
                else {
                    mid++;
                }
            }
        }
    };