-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabsoluteSort.java
71 lines (53 loc) · 1.47 KB
/
absoluteSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Absolute Value Sort
Given an array of integers arr, write a function absSort(arr), that sorts the array according to the absolute values of the numbers in arr. If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers.
Examples:
input: arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]
Constraints:
[time limit] 5000ms
[input] array.integer arr
0 ≤ arr.length ≤ 10
[output] array.integer
*/
import java.io.*;
import java.util.*;
class Solution {
static class IntComparator implements Comparator<Integer> {
public int compare(Integer i1, Integer i2) {
int ret = Integer.compare(Math.abs(i1),Math.abs(i2));
if( ret == 0){
if (i1 == i2) {
return 0;
}
return i1 > i2 ? 1:-1;
}
return ret;
}
}
static int[] absSort(int[] arr) {
// your code goes here
/*
[2, -7, -2, -2, 0]
l r
[0, -7, -2, -2, 2]
l r
[0, 2, -2, -2, 7]
l r
[0, -2, -2, 2, 7]
hint
*/
Integer[] newArray = new Integer[arr.length];
for (int i=0; i< arr.length; i++) {
newArray[i] = Integer.valueOf(arr[i]);
}
Arrays.sort(newArray,new IntComparator()); // [-7,-2,-2,0,2]
int[] array = new int[newArray.length];
for (int i=0; i< newArray.length; i++) {
array[i] = newArray[i].intValue();
}
return array;
}
public static void main(String[] args) {
}
}