Easy understand


  • 0
    S
    public class Solution {
        public void sortColors(int[] nums) {
            int i = -1;
            int j = nums.length;
            
            for (int k = 0; k < j; k++){
                if (nums[k] == 2){
                    swap(nums, k, --j);
                    k--;
                }else if (nums[k] == 0){
                    swap(nums, ++i, k);
                }
            }
            
        }
        
        public void swap(int[] nums, int i, int j){
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.