My Java solution


  • 0
    Q
    public class Solution {
        public static void sortColors(int[] nums) {
    		int start = 0, end = nums.length - 1;
    		for (int i = 0; i < nums.length; i++) {
    			if (nums[i] == 0 && i > start) {
    				swap(nums, i, start++);
    				i--;
    			}
    			if (nums[i] == 2 && i < end) {
    				swap(nums, i, end--);
    				i --;
    			}
    		}
    	}
    
    	private static void swap(int[] nums, int i, int j) {
    		// TODO Auto-generated method stub
    		int temp = nums[i];
    		nums[i] = nums[j];
    		nums[j] = temp;
    	}
    
    }
    

Log in to reply
 

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