최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
0 < array의 길이 < 100
0 ≤ array의 원소 < 1000
array result
[1, 2, 3, 3, 3, 4] 3
[1, 1, 2, 2] -1
[1] 1
입출력 예 #1
[1, 2, 3, 3, 3, 4]
에서 1은 1개 2는 1개 3은 3개 4는 1개로 최빈값은 3입니다.
입출력 예 #2
[1, 1, 2, 2]
에서 1은 2개 2는 2개로 최빈값이 1, 2입니다. 최빈값이 여러 개이므로 -1을 return 합니다.
입출력 예 #3
[1]
에는 1만 있으므로 최빈값은 1입니다.
import java.util.Arrays;
public class Solution {
public int solution(int[] array) {
int max = 0;
int index = -1;
// 배열 정렬
Arrays.sort(array);
// 카운팅 배열 초기화
int[] count = new int[array[array.length-1]+1];
// 각 수의 index 카운팅
for (int i = 0; i < array.length; i++) {
count[array[i]]++;
}
// 최빈값 찾기
for (int j = 0; j < count.length; j++) {
if (max < count[j]) {
max = count[j];
index = j; // 최빈값이 바뀔 때의 인덱스 (최빈값)
} else if (max == count[j]) {
index = -1; // 최빈값이 여러개인 경우 -1
}
}
return index;
}
}
class Solution {
public int solution(int price) {
double answer = 0;
if(price>99999&&price<300000){
answer = (price*0.95);
}
else if(price>299999 &&price < 500000){
answer = (price*0.9);
}else if(price > 499999){
answer = (price*0.8);
}
return (int)answer;
}
}
if의 가격 조건이 중요함. (첫번째부터 내려오며 실행되므로)
>=
(이상)의 조건 이므로 가장 큰 수를 첫 번째 조건으로 걸러야 합니다.
이하인 경우, 가장 작은 수부터 조건을 지정해야 합니다.
즉, 올바른 코드는
class Solution {
public int solution(int price) {
double answer = 0;
if( price >= 500000) {
answer = (price*0.8);
} else if( price >= 300000){
answer = (price * 0.9);
}else if (price >= 100000){
answer = (price * 0.95);
} else {
answer = price;
}
return (int)answer;
}
}