Skip to content

Commit d1c151f

Browse files
authored
Update Sort Colors.java
1 parent 8b4e255 commit d1c151f

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

Medium/Sort Colors.java

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,18 @@ class Solution {
22
public void sortColors(int[] nums) {
33
int zeroIdx = 0;
44
int twoIdx = nums.length - 1;
5-
int currIdx = 0;
6-
while (currIdx <= twoIdx) {
7-
if (nums[currIdx] == 0) {
8-
swap(nums, currIdx++, zeroIdx++);
9-
} else if (nums[currIdx] == 2) {
10-
swap(nums, currIdx, twoIdx--);
5+
for (int i = 0; i <= twoIdx; ) {
6+
if (nums[i] == 0 && i != zeroIdx) {
7+
int temp = nums[zeroIdx];
8+
nums[zeroIdx++] = nums[i];
9+
nums[i] = temp;
10+
} else if (nums[i] == 2 && i != twoIdx) {
11+
int temp = nums[twoIdx];
12+
nums[twoIdx--] = nums[i];
13+
nums[i] = temp;
1114
} else {
12-
currIdx++;
15+
i++;
1316
}
1417
}
1518
}
16-
17-
private void swap(int[] nums, int idxOne, int idxTwo) {
18-
int temp = nums[idxTwo];
19-
nums[idxTwo] = nums[idxOne];
20-
nums[idxOne] = temp;
21-
}
2219
}

0 commit comments

Comments
 (0)