[문제] 로또 최고순위와 최저순위
https://school.programmers.co.kr/learn/courses/30/lessons/77484
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
내 풀이
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// lottos_len은 배열 lottos의 길이입니다.
// win_nums_len은 배열 win_nums의 길이입니다.
int* solution(int lottos[], size_t lottos_len, int win_nums[], size_t win_nums_len) {
// return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
int* answer = (int*)malloc(sizeof(int) * 2);
// 정렬 없이 풀어보기
int match_count = 0;
int zero_count = 0;
for (size_t i = 0; i < win_nums_len; i++)
{
for (size_t j = 0; j < lottos_len; ++j)
{
if (win_nums[i] == lottos[j])
{
++match_count;
}
}
if (lottos[i] == 0)
{
++zero_count;
}
}
int max_result = 7 - (match_count + zero_count);
int min_result = 7 - match_count;
if (( match_count + zero_count ) == 0) max_result = 6;
if (match_count == 0) min_result = 6;
answer[0] = max_result;
answer[1] = min_result;
return answer;
}
풀이과정
2중 for loop으로 선택한 로또 숫자와 1등 로또숫자를 비교해서 일치하는 숫자를 저장
-> 만약 선택한 로또 숫자가 0이라면 0 개수 카운트를 증가시킴.
-> 최종 등수 결정.
개선점
이번 풀이에서는 선택한 로또 숫자와 1등 로또 숫자 둘을 정렬하지 않고 비교했는데, 정렬하고 비교하면 좀 더 효율적으로 개선할 수 있을까?
for loop 2개를 쓰지 않고 좀 더 복잡도를 감소시킬 방법이 있지 않을까.
-> 이 번호가 당첨 번호인지 바로 확인할 수 있는 표를 만들면 된다.
로또 번호 범위 bool win_table[46]
win_table[번호] = true면 당첨번호, false면 당첨번호 아님
로또 번호 개수가 6개라서 지금은 큰 영향은 없지만 이렇게 만들면 시간복잡도를 기존의 O(N * M)에서 O(win_nums_len + lottos_len)으로 줄일 수 있다.
'C언어 공부 > 코드 테스트 연습' 카테고리의 다른 글
| 2026/07/28 코드카타 (0) | 2026.07.28 |
|---|---|
| 2026/07/23 코드카타 (0) | 2026.07.23 |