-
[Leetcode] 75. Sort Colors 문제풀이Algorithm/문제풀이 2021. 10. 27. 20:40
https://leetcode.com/problems/sort-colors/
Sort Colors - LeetCode
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
문제 내용
컬러가 0,1,2 로 있는데 추가적인 공간을 사용하지 않고 정렬하는 문제이다.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
문제 풀이
숫자가 3개밖에 없기 때문에
왼쪽에는 0을 몰아주고
오른쪽에는 2를 몰아주는 방식으로 정렬하면 된다.
class Solution { public: void sortColors(vector<int>& nums) { int s = 0; int e = nums.size()-1; int i = 0; while(i <= e) { if (nums[i] == 0) { swap(nums[s], nums[i]); s++; i++; } else if (nums[i] == 2) { swap(nums[e], nums[i]); e--; } else { i++; } } } };
'Algorithm > 문제풀이' 카테고리의 다른 글
[Leetcode] 1721. Swapping Nodes in a Linked List 문제 풀이 (0) 2022.04.04 [Leetcode] 540. Single Element in a Sorted Array 문제풀이 (0) 2021.11.20 [Leetcode] 155. Min Stack 문제풀이 (0) 2021.10.25 [Leetcode] 543. Diameter of Binary Tree 문제풀이 (0) 2021.10.11 [Leetcode] 88. Merge Sorted Array 문제풀이 (0) 2021.10.08