-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1365.How-Many-Numbers-Are-Smaller-Than-the-Current-Number.java
66 lines (54 loc) · 1.6 KB
/
1365.How-Many-Numbers-Are-Smaller-Than-the-Current-Number.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
// https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
// algorithms
// Easy (88.4%)
// Total Accepted: 5,714
// Total Submissions: 6,464
// beats 100.0% of java submissions
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int len = nums.length;
int[] res = new int[len];
ArrayList<Tuple> l = new ArrayList<>();
HashMap<Integer, Tuple> map = new HashMap<>();
for (int i = 0; i < len; i++) {
Tuple tmp = map.get(nums[i]);
if (tmp == null) {
tmp = new Tuple(nums[i]);
map.put(nums[i], tmp);
l.add(tmp);
}
tmp.addIndex(i);
}
Collections.sort(l);
int tmp = 0;
for (int i = 0; i < l.size(); i++) {
ArrayList<Integer> indexList = l.get(i).getIndex();
for (int idx : indexList) {
res[idx] = tmp;
}
tmp += indexList.size();
}
return res;
}
class Tuple implements Comparable<Tuple> {
private int num;
private ArrayList<Integer> index;
Tuple(int num) {
this.num = num;
this.index = new ArrayList<>();
}
public void addIndex(int index) {
this.index.add(index);
}
public int getNum() {
return this.num;
}
public ArrayList<Integer> getIndex() {
return this.index;
}
@Override
public int compareTo(Tuple another) {
return this.num - another.num;
}
}
}