넘치게 채우기

[LeetCode] 905. Sort Array By Parity 본문

PS/LeetCode

[LeetCode] 905. Sort Array By Parity

riveroverflow 2023. 9. 28. 16:45
728x90
반응형

https://leetcode.com/problems/sort-array-by-parity/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

문제 유형 : 정렬

문제 난이도 : Easy

 

문제

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

 

짝수가 배열의 앞, 홀수가 배열의 뒤쪽에 오도록 하라.

 

풀이

람다 함수를 정의해서, 두 수중 짝수인 수를 앞으로 하고, 같은 짝수끼리는 더 작은수를 앞으로 해주기로 했다.

 

코드

C++

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        sort(nums.begin(), nums.end(), [](const int &a, const int &b) {

            if (a % 2 == 0 && b % 2 == 0)
                return a < b;
            else if (a % 2 != 0 && b % 2 != 0)
                return a > b;
            else if (a % 2 == 0)
                return true;
            else
                return false;
        });

        return nums;
    }
};
 
728x90
반응형

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 456. 132 Pattern  (0) 2023.09.30
[LeetCode] 896. Monotonic Array  (0) 2023.09.29
[LeetCode] 1048. Longest String Chain  (0) 2023.09.23
[LeetCode] 377. Combination Sum IV  (0) 2023.09.09
[LeetCode] 141. Linked List Cycle  (0) 2023.09.04