문제
내가 작성한 정답
class Solution {
public int solution(int[] arr1, int[] arr2) {
int f = arr1.length;
int s = arr2.length;
if(f==s){
int sum1 = 0;
int sum2 = 0;
for(int i : arr1){
sum1 += i;
}
for(int i: arr2){
sum2 += i;
}
return sum1==sum2? 0: sum1>sum2?1:-1;
} else {
return f>s?1:-1;
}
}
}
다른 사람들의 정답
import java.util.stream.IntStream;
class Solution {
public int solution(int[] arr1, int[] arr2) {
int answer = Integer.compare(arr1.length, arr2.length);
if(answer == 0) {
answer = Integer.compare(IntStream.of(arr1).sum(), IntStream.of(arr2).sum());
}
return answer;
}
}
Integer.compare(x, y)
• x > y → 1 반환
• x < y → -1 반환
• x == y → 0 반환
- IntStream 생성
IntStream.of(int... values): 주어진 int 값들로 스트림을 생성
IntStream.range(int startInclusive, int endExclusive): 주어진 범위의 int 값들로 스트림을 생성
IntStream.rangeClosed(int startInclusive, int endInclusive): 주어진 범위의 int 값들로 스트림을 생성하되, 끝 값도 포함
- 중간연산
map(IntUnaryOperator mapper): 각 요소에 주어진 함수를 적용하여 새로운 스트림을 생성
filter(IntPredicate predicate): 조건에 맞는 요소만 필터링하여 새로운 스트림을 생성
distinct(): 중복 요소를 제거
- 최종 연산
forEach(IntConsumer action): 각 요소에 대해 주어진 동작을 수행
sum(): 모든 요소의 합을 계산
average(): 평균을 계산
min(), max(): 최소값 또는 최대값 반환
collect(): 결과를 수집하여 컬렉션으로 변환
Share article