fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void solve(vector<int> &nums) {
  5. // Time: O(n * log(n)), Space: O(1)
  6. // sort(nums.begin(), nums.end());
  7.  
  8. // Time: O(n), Space: O(n)
  9. int zeros = 0, ones = 0, twos = 0;
  10. for (int i = 0; i < nums.size(); i++) {
  11. switch (nums[i]) {
  12. case 0:
  13. zeros++;
  14. break;
  15. case 1:
  16. ones++;
  17. break;
  18. case 2:
  19. twos++;
  20. break;
  21. }
  22. }
  23. for (int i = 0; i < zeros; i++) {
  24. nums[i] = 0;
  25. }
  26. for (int i = zeros; i < zeros + ones; i++) {
  27. nums[i] = 1;
  28. }
  29. for (int i = zeros + ones; i < nums.size(); i++) {
  30. nums[i] = 2;
  31. }
  32.  
  33. // Time: O(n), Space: O(1)
  34.  
  35. }
  36.  
  37. void print(vector<int> &nums) {
  38. for (int i = 0; i < nums.size(); i++) {
  39. cout << nums[i] << " ";
  40. }
  41. cout << endl;
  42. }
  43.  
  44. int main() {
  45. int n;
  46. cin >> n;
  47. vector<int> nums(n);
  48. for (int i = 0; i < n; i++) {
  49. cin >> nums[i];
  50. }
  51. solve(nums);
  52. print(nums);
  53. }
Success #stdin #stdout 0.01s 5288KB
stdin
6
2 0 2 1 1 0
stdout
0 0 1 1 2 2