Iterator iter = set.iterator(); // Iterator 사용
while(iter.hasNext()) {//값이 있으면 true 없으면 false
System.out.println(iter.next());
}
import java.util.Arrays;
import java.util.Set;
import com.google.common.collect.Sets;
public class SetToArray {
public static void main(String[] args) {
// Set 객체
Set<Integer> set = Sets.newHashSet(1, 2, 3, 4); // Set -> 배열
Integer[] arr = set.toArray(new Integer[0]);
//배열의 크기를 0으로 지정하면 자동으로 배열의 크기 지정
// 배열 출력
System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4]
}}
Arrays.sort(arr1,Collections.reverseOrder());
✔️ 답은 맞는데 시간초과이다...
import java.util.*;
public class Main {
public static int solution(int A, int B, int[] arr){
Set<Integer> set = new TreeSet();
for(int i=0;i<A;i++) {
for(int j=0;j<A;j++) {
for(int z=0;z<A;z++) {
if(i!=j &&j!=z&&z!=i)set.add(arr[i]+arr[j]+arr[z]);
}
}
}
Integer[] arr1 = set.toArray(new Integer[0]);
Arrays.sort(arr1,Collections.reverseOrder());
return arr1[B-1];
}
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
int A = kb.nextInt();
int B = kb.nextInt();
int[] arr = new int[A];
for(int i=0;i<A;i++) {
arr[i]=kb.nextInt();
}
System.out.println(solution(A,B,arr));
}
}
✔️강의 답
import java.util.*;
public class Main {
public static int solution(int A, int B, int[] arr){
Set<Integer> set = new TreeSet<>(Collections.reverseOrder());
for(int i=0;i<A;i++) {
for(int j=i+1;j<A;j++) {
for(int z=j+1;z<A;z++) {
set.add(arr[i]+arr[j]+arr[z]);
}
}
}
int c=0;
for(int x : set){
c++;
if(c==B) return x;
}
return -1;
}
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
int A = kb.nextInt();
int B = kb.nextInt();
int[] arr = new int[A];
for(int i=0;i<A;i++) {
arr[i]=kb.nextInt();
}
System.out.println(solution(A,B,arr));
}
}