엔지니어 게시판
LeetCode 솔루션 분류

[5/2] 905. Sort Array By Parity

컨텐츠 정보

본문

[LeetCode 시즌 3] 2022년 5월 2일 문제입니다.

https://leetcode.com/problems/sort-array-by-parity/


[Easy] 905. Sort Array By Parity

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.

 

Example 1:

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:

Input: nums = [0]
Output: [0]

 

Constraints:

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

관련자료

댓글 4

나무토끼님의 댓글

  • 익명
  • 작성일
Runtime: 117 ms, faster than 37.62% of Python3 online submissions for Sort Array By Parity.
Memory Usage: 14.6 MB, less than 63.70% of Python3 online submissions for Sort Array By Parity.
class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        p1, p2 = 0, len(nums) - 1
        while p1 < p2:
            if nums[p1] % 2 == 1 and nums[p2] % 2 == 0:
                nums[p1], nums[p2] = nums[p2], nums[p1]    
            while p1 < len(nums) and nums[p1] % 2 == 0:
                p1 += 1
            while p2 >= 0 and nums[p2] % 2 == 1:
                p2 -= 1
        return nums        
                

dkim1017님의 댓글

  • 익명
  • 작성일
Runtime: 162 ms
Memory Usage: 46.3 MB
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArrayByParity = function(nums) {
  parityArray = []
  for (var i = 0; i < nums.length; i++) {
    if (nums[i] % 2 === 0) {
      parityArray.push(nums.splice(i,1))
      i--;
    }
  }
  for (var i = 0; i < nums.length; i++) {
    parityArray.push(nums[i]);
  }
  return parityArray.flat()
};

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 15 ms, faster than 48.12% of C++ online submissions for Sort Array By Parity.
Memory Usage: 16.3 MB, less than 25.41% of C++ online submissions for Sort Array By Parity.
class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        int p = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] % 2 == 0) {
                swap(nums[p++], nums[i]);
            }
        }
        return nums;
    }
};

austin님의 댓글

  • 익명
  • 작성일
class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        for(auto [slow, fast] = tuple(nums.begin(), nums.begin()); fast != nums.end(); ++fast) {
            if (!(*fast%2)) swap(*(slow++), *fast);
        }
        return nums;
    }
};
전체 94 / 4 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0