public class phoneGetMon {
public static void main(String[] args) {
int[] nums = {3,1,2,3};
int answer = solution(nums);
System.out.println(answer);
}
private static int solution(int[] nums) {
int answer = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]==nums[j]) {
nums[j] = -1;
}
}
if(nums[i]!=-1) {
count++;
}
}
System.out.println("count : "+count);
System.out.println("nums.length/2 : "+nums.length/2);
if(count>nums.length/2) {
answer=nums.length/2;
}else {
answer=count;
}
return answer;
}
}
문제가 많이 간단했다.
하지만 문제는...다른 사람의 풀이는 나보다 더 간단했다!
stream과 collector를 사용했던데 어떤건지 너무 낯설다.. 찾아봐야겠다
===============================================
map이나 set을 이용하면 중복을 제거할 수 있는데 이것또한 응용할 수 있었겠다..
참고한 다른 사람의 풀이이다..
import java.util.Arrays;
import java.util.stream.Collectors;
class Solution {
public int solution(int[] nums) {
return Arrays.stream(nums)
.boxed()
.collect(Collectors.collectingAndThen(Collectors.toSet(),
phonekemons -> Integer.min(phonekemons.size(), nums.length / 2)));
}
}
'코딩테스트 연습' 카테고리의 다른 글
로그인후 결제를 간단하게 로그화해보는 알고리즘 (0) | 2021.08.22 |
---|---|
채점하기.. 본인이 채점한 점수가 최고값,최소값일 경우는 제외하고 (0) | 2021.08.20 |
체육복 서로 빌려줘 수업받을 수 있는 인원 확인하는 코드 (0) | 2021.08.20 |
일정한 형식의 답안을 제출하는 학생들중 최대 정답자명단 뽑기 (0) | 2021.08.20 |
배열의 일부를 정렬하고 정렬한 수 중에 k 번째 수를 구하라. (0) | 2021.08.20 |