905. Sort Array By Parity

inhalin·2021년 2월 25일
0

Leetcode Easy

목록 보기
12/14

문제

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

음수가 없는 정수의 배열이 주어질 때, 모든 짝수 요소들이 앞에 오고 홀수들이 뒤따르는 배열을 반환하라.

Example 1:

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

Note:

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

Solution

  1. 배열의 시작과 끝을 가리키는 가상의 포인터 두개를 만들어준다.
  2. 두 요소를 2로 나눈 나머지를 각각 변수에 저장한다. 0이면 짝수, 1이면 홀수이다.
  3. 만약 i번째 나머지가 0이면 다음 요소로 이동한다.
  4. i번째 나머지가 0(짝수)이고 j번째 나머지가 0이 아니면(홀수) i를 다음 요소로 이동한다.
  5. 만약 j번째가 홀수이면 j를 앞으로 이동한다.
  6. j번째가 홀수이고 i번째가 짝수이면 서로 위치를 바꿔준다.
  7. 두 인덱스값의 차가 1보다 작아지면 반복문을 나간다.
class Solution {
    public int[] sortArrayByParity(int[] A) {
        int i = 0;
        int j = A.length-1;
        
        while(j-i >= 1){
            int temp;
            int begin = A[i]%2;
            int end = A[j]%2;
            
            if(begin == 0){
                i++;
            } else if (begin == 0 && end != 0){
                i++;
            } else if (end != 0){
                j--;
            } else if (begin != 0 && end == 0){
                temp = A[j];
                A[j] = A[i];
                A[i] = temp;
                i++;
                j--;
            }
        }
        return A;
    }
}

0개의 댓글