-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-11 Sort Colors
More file actions
36 lines (32 loc) · 1021 Bytes
/
Day-11 Sort Colors
File metadata and controls
36 lines (32 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public void sortColors(int[] nums) {
//Approach one -- (Counting Sort : Double pass}
int[] colorCount = new int[3];
for(int num : nums) {
colorCount[num]++;
}
int i = 0;
for(int index = 0; index < colorCount.length; index++) {
int count = colorCount[index];
while(count > 0){
nums[i++] = index;
count--;
}
}
}
}
class Solution {
public void sortColors(int[] nums) {
int start=0,end=nums.length-1,currentPosition=0;
while(currentPosition<=end){
if(nums[currentPosition]==0) swap(nums,start++,currentPosition++);
else if(nums[currentPosition]==2) swap(nums,currentPosition,end--);
else currentPosition++;
}
}
public void swap(int[] nums,int start,int end){
int temp=nums[start];
nums[start]=nums[end];
nums[end]=temp;
}
}