본문 바로가기

알고리즘

짝수 홀수 개수 자바

정수가 담긴 리스트 num_list가 주어질 때, num_list의 원소 중 짝수와 홀수의 개수를 담은 배열을 return 하도록 solution 함수를 완성해보세요.

 

입출력 예

num_listresult

[1, 2, 3, 4, 5] [2, 3]
[1, 3, 5, 7] [0, 4]

 

 

기존에 내가 풀었던 코드

import java.util.ArrayList;

class Solution {
    public ArrayList<ArrayList<Integer>> solution(int[] num_list) {
        ArrayList<Integer> evenList = new ArrayList<>();
        ArrayList<Integer> oddList = new ArrayList<>();
        // 짝수와 홀수의 개수를 저장할 변수
        int evenCnt = 0;
        int oddCnt = 0;

        // num_list를 순회하며 짝수와 홀수를 카운트
 	   for(int i=0; i <num_list.length; i++ ){
            if(num_list[i] % 2 == 0){
           
                evenList.add(num_list[i]);
                evenCnt++;
            }else{
                oddCnt++;
                oddList.add(num_list[i]);  
                
            }
        }

        // 결과를 배열로 반환
        return new int[]{evenCnt, oddCnt};
    }
}

 

이렇게 풀고 사람들 풀이를 봤다

 

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[2];
        

            for(int i =0; i< num_list.length; i++){
            
            answer[num_list[i] % 2]++;
        }; 
        return answer;
    }
}

 

풀이를 보고 이마를 탁 쳤다..

짝수 홀수밖에 없으니 배열의 크기를 미리 설정한것, 배열의 해당 위치 값을 1 증가시킨것
즉, 짝수면 answer[0]을 증가시키고, 홀수면 answer[1]을 증가

이렇게 풀이하니 따로 변수선언을 하지않아도 되는점 등 ..

 

사람들 코드를 보며 더 공부해야겠다 갈길이 너무멀다ㅜㅜ

'알고리즘' 카테고리의 다른 글

자바 배열  (0) 2026.08.05
배열 회전시키기  (0) 2024.11.22
합병정렬  (1) 2024.09.23
분할정복 알고리즘  (0) 2024.09.21
알고리즘의 효율성  (2) 2024.09.21