문제
내가 작성한 정답
import java.util.*;
class Solution {
public int[] solution(int[] numlist, int n) {
int[] answer = new int[numlist.length];
Set<Integer> set = new TreeSet<>();
Map<Integer,List<Integer>> map = new HashMap<>();
for(int i:numlist){
int dist = Math.abs(i-n);
set.add(dist);
map.computeIfAbsent(dist,k->new ArrayList<>()).add(i);
}
int idx =0;
for(int i:set){
List<Integer> in = map.get(i);
in.sort(Collections.reverseOrder());
for(int k:in){
answer[idx++] = k;
}
}
return answer;
}
}
class Solution {
public int[] solution(int[] numlist, int n) {
int[] answer = new int[numlist.length];
Map<Integer,List<Integer>> map = new TreeMap<>();
for(int i:numlist){
int dist = Math.abs(i-n);
map.computeIfAbsent(dist,k->new ArrayList<>()).add(i);
}
int idx =0;
for(List<Integer> i:map.values()){
List<Integer> in = map.get(i);
in.sort(Collections.reverseOrder());
for(int k:in){
answer[idx++] = k;
}
}
return answer;
}
}다른 사람들의 정답
import java.util.Arrays;
class Solution {
public int[] solution(int[] numList, int n) {
return Arrays.stream(numList)
.boxed()
.sorted((a, b) -> Math.abs(a - n) == Math.abs(b - n) ? b.compareTo(a) : Integer.compare(Math.abs(a - n), Math.abs(b - n)))
.mapToInt(Integer::intValue)
.toArray();
}
}
import java.util.*;
class Solution {
public int[] solution(int[] numlist, int n) {
int size = numlist.length;
for(int i=0; i<size-1; i++){
for(int k=i+1; k<size; k++){
int a = (numlist[i] - n) * (numlist[i] > n ? 1 : -1);
int b = (numlist[k] - n) * (numlist[k] > n ? 1 : -1);
if(a > b || (a == b && numlist[i] < numlist[k])){
int temp = numlist[i];
numlist[i] = numlist[k];
numlist[k] = temp;
}
}
}
return numlist;
}
}
import java.util.*;
class Solution {
public int[] solution(int[] numlist, int n) {
return Arrays.stream(numlist).mapToObj(a->(Integer)a)
.sorted((a, b)->{
int u = Math.abs(n - a);
int v = Math.abs(n - b);
if(u == v) return b - a;
else return u - v;
})
.mapToInt(a->a)
.toArray();
}
}
import java.util.*;
class Solution {
class Number implements Comparable<Number> {
int n;
int target;
Number(int n, int target) {
this.n = n;
this.target = target;
}
public int compareTo(Number other) {
if (Math.abs(target - n) == Math.abs(target - other.n)) {
return other.n - n;
}
return Math.abs(target - n) - Math.abs(target - other.n);
}
}
public int[] solution(int[] numlist, int n) {
Number[] numbers = new Number[numlist.length];
for (int i = 0; i < numlist.length; ++i) {
numbers[i] = new Number(numlist[i], n);
}
Arrays.sort(numbers);
for (int i = 0; i < numlist.length; ++i) {
numlist[i] = numbers[i].n;
}
return numlist;
}
}Share article