-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSort0,1,2color_75
47 lines (44 loc) · 1.07 KB
/
Sort0,1,2color_75
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
37
38
39
40
41
42
43
44
45
46
47
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. sort the three
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
my code -
class Solution {
public void sortColors(int[] nums) {
int z =0 , o=0, t=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==0)
z++;
else if(nums[i]==1)
o++;
else
t++;
}
for(int i=0;i<nums.length;i++){
if(z!=0)
{nums[i]=0;z--;}
else if(o!=0)
{
nums[i]=1; o--;
}
else
nums[i]=2;
}
}
}
I Got 100 beats but still far better code -
class Solution {
public void sortColors(int[] nums) {
int[] temp = new int[3];
for(int i=0;i<nums.length;i++){
temp[nums[i]]++;
}
int k=0;
for(int j=0;j<temp.length;j++){
while(temp[j]>0){
nums[k]=j;
k++;
temp[j]--;
}
}
}
}