🔺 문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
🔺 코드 (틀림)
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int[] answer;
if(arr.length == 1) {
answer = new int[]{-1};
} else {
// int 배열 내림차순 정렬
// : Integer 타입 배열로 변경해야 함.
Integer[] realArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(realArr, Collections.reverseOrder());
answer = new int[arr.length - 1];
for(int i=0 ; i < answer.length ; i++) {
answer[i] = realArr[i];
}
}
return answer;
}
}
int배열은 내림차순 정렬할 때 Collections.reverseOrder()
가 안 된다고 해서,
블로그 글을 참고해서 Integer 배열로 바꿔줬는데..!
Integer[] realArr = Arrays.stream(arr).boxed().toArray(Integer::newValue);
Arrays.sort(realArr, Collections.reverseOrder());
(참고)
[JAVA] int, String 배열의 오름차순, 내림차순 정렬
java에서 정렬할 때는 Arrays라는 java.util에 포함된 클래스를 이용해야 한다. import java.util.ArraysString String 타입일 때는 비교적 쉽게 내림차순 정렬이 가능하다.intint 타입일 때는 위와 같은 방법으로
velog.io
왜 안 될까 싶어서 질문하기를 보았고...
정렬하라는 얘기가 없었어서 틀렸다고 한다..
그래서 이것저것 고민하다가 다른 분 코드를 보기로 했다,,,ㅠ
[프로그래머스]제일 작은 수 제거하기(JAVA)
문제 설명 정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요. 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. 예를들어 a
grandma-coding.tistory.com
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
// 배열 길이가 1인 경우
if(arr.length == 1) {
int[] answer = {-1};
return answer;
}
// 그게 아닌 경우
int[] answer = new int[arr.length - 1];
int min = arr[0];
for(int i : arr) {
min = Math.min(min, i);
}
int idx = 0;
for(int i=0 ; i < arr.length ; i++) {
if(arr[i] == min) {
continue;
}
answer[idx++] = arr[i];
}
return answer;
}
}
나는 19-27번째 줄을 잘 생각하지 못 했다....
첨에 리스트로 해버릴까,, 했었는디,,, 암튼,,,
저 idx를 사용한 이유는 가장 작은 수가 여러개일 수도 있기 때문이라고,,,!
i를 넣으면 안 되는걸까?하고 넣어봤는데 실패한다.
아무튼 만만하게 생각했는데 생각보다 시간이 넘 오래걸려서 당황스럽지만... 그래도 해결,,,
다른 분들 풀이도 보다가 개인적으로 원하던 코드들을 찾았다
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public int[] solution(int[] arr) {
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
Arrays.sort(arr);
list.remove(list.indexOf(arr[0]));
if (list.size() <= 0) return new int[]{-1};
return list.stream().mapToInt(i->i).toArray();
}
}
stream 조금만 이해하니까 이제 저 정도는 알겠다.
그리고 내가 리스트 써야지- 하고 생각만 하던 리스트 방식을 활용하셨다!!!
내가 놓친 부분이 뭐였냐 하면!
리스트를 썼을 때, 그 최소값이 들어있는 인덱스 값을 리스트에서 remove해주면 되는 부분이었다,,,!!!
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int[] answer = {};
if (arr.length == 1) {
answer = new int[]{-1};
} else {
List<Integer> list = new ArrayList<>();
for (int a : arr)
list.add(a);
list.remove(Collections.min(list));
answer = new int[arr.length - 1];
for (int i = 0; i < list.size(); i++)
answer[i] = list.get(i);
}
return answer;
}
}
여기서는 배열 내의 최솟값을 찾을 때 Collections.min(list)
를 활용하셨다.. 멋지다
(참고)
✔ 컬렉션 최소값 최대값 구하기
[Java]컬렉션(Collection) 최소값 최대값 구하기
이번 포스팅에서는 Java의 컬렉션(Collection)에서 최소 또는 최대 값을 가져오는 방법들을 소개합니다. Collections.min() 메서드와 Collections.max() 메서드 Java Collection Framework는 개발자가 컬렉션을 쉽게
developer-talk.tistory.com
[Java] 최소/최대 원소 구하기 (Loop/Collections/Stream)
Engineering Blog by Dale Seo
www.daleseo.com
'코테 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Lv. 1] 자연수 뒤집어 배열로 만들기 (0) | 2023.02.25 |
---|---|
[프로그래머스/Lv. 1] 음양 더하기 (0) | 2023.02.24 |
[프로그래머스/Lv. 1] 정수 제곱근 판별 (0) | 2023.02.24 |
[프로그래머스/Lv. 1] 문자열 내림차순으로 배치하기 (0) | 2023.02.24 |
[프로그래머스/Lv. 1] 약수의 개수와 덧셈 (0) | 2023.02.24 |