import java.util.*;
class Solution {
public int solution(int[] array) {
int answer = 0;
int[] count = new int[100];
for(int i=0;i<array.length;i++) {
count[array[i]]+=1;
}
Arrays.sort(count);
answer = count[count.length-1];
if(count.length==0){
answer = array[0];
}
if(count[count.length-1]==count[count.length-2]){
answer = -1;
}
return answer;
}
}
위의 코드는 런타임 에러가 발생한다.
import java.util.*;
class Solution {
public int solution(int[] array) {
int answer = 2;
int[] count = new int[100];
Arrays.sort(array);
System.out.println(Arrays.toString(array));
for(int i=0;i<array.length-1;i++) {
if(array[i]==array[i+1]) {
count[array[i]]++;
}
}
for(int i = 0;i<99;i++) {
if(count[i]<count[i+1]) {
answer =i+1;
}else if(count[i]!=0&& (count[i]==count[i+1])) {
answer = -1;
break;
}
}
if(array.length==1) {
answer = array[0];
return answer;
}
return answer;
}
}
위로 수정했는데도 계속 런타임에러 발생중임
import java.util.*;
class Solution {
public int solution(int[] array) {
int answer = 0;
//빈도수를 저장할 count배열선언
//빈도수를 저장할 count배열선언
int[] count = new int[1000];
//array에 똑같은 값이 있으면 count변수에 그 값을 인덱스로 저장.
for(int i=0;i<array.length;i++) {
for(int t=i+1; t<array.length;t++){
if(array[i]==array[t]) {
count[array[i]]+=1;
}
}
}
int max = 0;
for(int i = 0; i<count.length;i++) {
if(count[i]>max) {
answer = i;
}
}
Arrays.sort(count);
if(count[count.length-1]==count[count.length-2]){
answer = -1;
}
if(array.length ==1) {
answer = array[0];
}
return answer;
}
}
성공! 드디어 풀었다.
import java.util.Arrays;
public class Test2 {
public static void main(String[] args) {
int answer = 0;
int[] array = {1,1,2,2,2};
int[] count = new int[array.length];
int max = 0;
if(array.length==1) {
answer = array[0];
}else {
for(int i=0;i<array.length;i++) {
System.out.print("i:"+array[i]);
for(int j=0; j<i;j++) {
if(array[i]==array[j]) {
System.out.print(j+"j:"+array[i]);
count[i] +=1;
}
}
System.out.println();
}
max=count[0];
//count 배열의 최대값 연산
for(int i=0;i<count.length;i++) {
if(max<count[i]) {
max = count[i];
System.out.println("max연산중"+i);
answer = array[i];
}
}
System.out.println("count배열"+Arrays.toString(count));
Arrays.sort(count);
if(count[count.length-1]==(count[count.length-2])) {
answer = -1;
}
}
System.out.println("answer : "+answer);
}
}
if(max<count[i]) {
max = array[i];
System.out.println("max연산중"+i);
이렇게 하고 왜 안되지 하고 있었는데, max와 count[i]를 비교할 때는 count[i]를 대입해야되는데 array[i]를 대입하고 있었다,
max에 count[i]를 대입하고
answer변수에 array[i]를 대입했더니 문제가 해결되었다!
'CS > 프로그래머스코딩테스트' 카테고리의 다른 글
2중 for문 주의점 (0) | 2023.09.18 |
---|---|
배열 원소의 길이 (0) | 2023.09.14 |
List를 Array로 변환하기 (0) | 2023.08.29 |
배열의 중앙값 구하기 (0) | 2023.04.17 |
레벨0. 분수의 덧셈 (0) | 2023.04.14 |