코딩테스트
75. Sort Colors
nayoon
2024. 2. 18. 20:02
https://leetcode.com/problems/sort-colors/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
0ms
class Solution {
public void sortColors(int[] nums) {
int[] count = new int[3];
for(int num: nums) {
count[num]++;
}
int index = 0;
for(int i = 0; i < nums.length; i++) {
if (count[index] == 0) {
index++;
i--;
continue;
}
nums[i] = index;
count[index]--;
}
}
}
0ms
class Solution {
public void sortColors(int[] nums) {
int l = 0;
int m = 0;
int h = nums.length - 1;
while(m <= h) {
if (nums[m] == 0) {
swap(nums, l, m);
l++;
m++;
} else if (nums[m] == 1) {
m++;
}
else if (nums[m] == 2) {
swap(nums, m, h);
h--;
}
}
}
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}