티스토리 뷰
주어진 코드
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n, int votes[], int votes_len) {
int arr[101] = { 0, };
for (int i = 0; i < votes_len; i++) {
arr[votes[i]]++;
}
for (int i = 1; i < n + 1; i++)
if (arr[i] > n / 2) //이때 n은 후보의 수 이다.
return i;
return -1;
}
int main() {
int n1 = 3;
int votes1[7] = { 1, 2, 1, 3, 1, 2, 1 };
int votes_len1 = 7;
int ret1 = solution(n1, votes1, votes_len1);
printf("solution 함수의 반환 값은 %d 입니다.\n", ret1);
int n2 = 2;
int votes2[7] = { 2, 1, 2, 1, 2, 2, 1 };
int votes_len2 = 7;
int ret2 = solution(n2, votes2, votes_len2);
printf("solution 함수의 반환 값은 %d 입니다.\n", ret2);
}
완성 코드
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int solution(int n, int votes[], int votes_len) {
int arr[101] = { 0, };
for (int i = 0; i < votes_len; i++) {
arr[votes[i]]++;
}
for (int i = 1; i < n + 1; i++)
if (arr[i] > votes_len / 2) //과반수는 투표한 인원의 과반수이어야 올바른 값이 나온다.
return i;
return -1;
}
int main() {
int n1 = 3;
int votes1[7] = { 1, 2, 1, 3, 1, 2, 1 };
int votes_len1 = 7;
int ret1 = solution(n1, votes1, votes_len1);
printf("solution 함수의 반환 값은 %d 입니다.\n", ret1);
int n2 = 2;
int votes2[7] = { 2, 1, 2, 1, 2, 2, 1 };
int votes_len2 = 7;
int ret2 = solution(n2, votes2, votes_len2);
printf("solution 함수의 반환 값은 %d 입니다.\n", ret2);
}
n/2를 사용하여 과반수를 계산하면, 후보의 수 사이에서의 과반수를 계산하기 때문에,
올바른 값이 나오기 위해서는 투표를 한 사람, votes_len의 과반수로 계산해야 한다.
n/2 -> votes_len/2
예시
n | vote | vote_len | return | |
예시 1 | 3 | [1, 2, 1, 3, 1, 2, 1] | 7 | 1 |
예시 2 | 2 | [2, 1, 2, 1, 2, 2, 1] | 7 | 2 |
goorm
구름은 클라우드 기술을 이용하여 누구나 코딩을 배우고, 실력을 평가하고, 소프트웨어를 개발할 수 있는 클라우드 소프트웨어 생태계입니다.
www.goorm.io
'[코테] > [GroomEdu]' 카테고리의 다른 글
[COS PRO 2급] 4차 10번_XX시험 합격자 수 구하기 (C/C++) (0) | 2021.05.22 |
---|---|
[COS PRO 2급] 4차 7번_오른 점수와 떨어진 점수 구하기 (C/C++) (0) | 2021.05.21 |
[COS PRO 2급] 4차 5번_다이어트하는 A씨의 추가 운동 여부 알려주기 (C/C++) (0) | 2021.05.20 |
[COS PRO 2급] 4차 6번_여러분이 열심히 모은 point, 돌려 드립니다 (C/C++) (0) | 2021.05.20 |
[COS PRO 2급] 4차 4번_조교의 수 구하기 (C/C++) (0) | 2021.05.19 |
댓글
공지사항
최근에 올라온 글
TAG
- YBM
- 구름 기출문제
- YBM기출
- 배열활용문제
- 프로그래머스
- programmers
- C++
- lv1
- Java
- 자바
- groom
- groomedu
- c언어
- cospro기출
- Cos Pro
- 구름에듀 기출문제
- 기출문제
- cospro기출문제
- CosPro
- lv2
- 알고리즘
- 코스프로
- 배열
- 코딩테스트
- C
- 구름에듀
- c언어 기출문제
- 연습문제
- 1급
- COSPRO 2급
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함