Wednesday, November 18, 2015

[leetcode] Sort Colors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public void sortColors(int[] nums) {
        int left = 0;
        int right = nums.length-1;
        int i = 0;
        while (i <= right){
            if (nums[i] == 0){
                swap(nums, i++, left++);
            }else if (nums[i] == 1){
                i++;
            }else if (nums[i] == 2){
                swap(nums, i, right--);
            }
        }
    }
    
    private void swap(int []nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

No comments:

Post a Comment