-
[Leetcode] 922. Sort Array By Parity II 문제 풀이Algorithm/문제풀이 2021. 9. 28. 23:39
https://leetcode.com/problems/sort-array-by-parity-ii/
Sort Array By Parity II - 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
문제 내용
i가 홀수이면 num[i] 도 홀수로,
i가 짝수이면 num[i] 도 짝수가 되도록 정렬하는 문제
Example 1:
Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
문제 풀이
홀짝으로 index를 나눠서 swap하면 된다.
i를 짝수 인덱스
j를 홀수 인덱스 라고 하면
i가 홀수, j가 짝수인 지점을 찾아서 swap을 했다.
class Solution { public: vector<int> sortArrayByParityII(vector<int>& nums) { int i = 0; int j = 1; while(1) { while(i < nums.size() && nums[i]%2 == 0) { i+=2; } if (i >= nums.size()) break; while(j < nums.size() && nums[j]%2 == 1) { j+=2; } if (j >= nums.size()) break; swap(nums[i], nums[j]); i+=2; j+=2; } return nums; } };
'Algorithm > 문제풀이' 카테고리의 다른 글
[Leetcode] 55. Jump Game 문제풀이 (0) 2021.09.29 [Leetcode] 213. House Robber II 문제 풀이 (0) 2021.09.29 [Leetcode] 929. Unique Email Addresses 문제 풀이 (0) 2021.09.27 [Leetcode] Shortest Path in a Grid with Obstacles Elimination 문제 풀이 (0) 2021.09.25 [Leetcode] 1137. N-th Tribonacci Number 문제 풀이 (0) 2021.09.24