Clean Java, human friendly


  • 1
    J
    public class Solution {
        private void swap(int[] nums, int i, int j){
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        public void sortColors(int[] nums) {
            // j is the index right after "end of 0", 
            // k is the index right before "head of 2"
            // i is the traveler
            int j = 0, k = nums.length-1;
            int i = 0;
            while(i <= k){
                if (nums[i] == 0 && i != j)
                    swap(nums, i, j++);
                else if (nums[i] == 2 && i != k)
                    swap(nums, i, k--);
                else i++;
            }
        }
    }
    

Log in to reply
 

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