Created
October 4, 2018 07:15
-
-
Save hsaputra/b6012f9c862a7e6a015edcd53df46f18 to your computer and use it in GitHub Desktop.
Sort Colors - https://leetcode.com/problems/sort-colors/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public void sortColors(int[] nums) { | |
// nums value is 0, 1, 2 | |
int left = 0; | |
int right = nums.length-1 ; | |
int i = 0; | |
// move 0s and 2s so 1s will settle by themselves | |
while (i < nums.length && i <= right && left < nums.length) { | |
// If i is 0 then move it to left. | |
if (nums[i] == 0) { | |
swap(i, left, nums); | |
left++; | |
i++; | |
} else if (nums[i] == 2) { | |
swap(i, right, nums); | |
right--; | |
} else { | |
i++; | |
} | |
} | |
} | |
private void swap(int i, int j, int[] nums) { | |
//System.out.println("Swap " + i + " with " + j); | |
int tmp = nums[i]; | |
nums[i] = nums[j]; | |
nums[j] = tmp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment