LC.P2418[按身高排序]

方法一:排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public String[] sortPeople(String[] names, int[] heights) {
int n = names.length;
int[][] index = new int[n][2];
for (int i = 0; i < n; ++i) {
index[i] = new int[]{heights[i], i};
}
Arrays.sort(index, (a, b) -> b[0] - a[0]);
String[] ans = new String[n];
for (int i = 0; i < n; ++i) {
ans[i] = names[index[i][1]];
}
return ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$

方法二:排序

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public String[] sortPeople(String[] names, int[] heights) {
int n = names.length;
Integer[] index = new Integer[n];
for (int i = 0; i < n; ++i) index[i] = i;
Arrays.sort(index, (a, b) -> heights[b] - heights[a]);
String[] ans = new String[n];
for (int i = 0; i < n; ++i) {
ans[i] = names[index[i]];
}
return ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$