除了以上方法,我们还可以创建一个索引数组 indices,其中 indices}[i] = i。排序完成后,对于所有的 i, j~(i\lt j) 都有 heights}[\textit{indices}[i]] > \textit{heights}[\textit{indices}[j]]。然后我们遍历 i 从 0 到 n-1,将 names}[\textit{indices}[i]] 追加到答案数组中。
代码
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: vector<string> sortPeople(vector<string>& names, vector<int>& heights){ int n = names.size(); vector<int> indices(n); iota(indices.begin(), indices.end(), 0); sort(indices.begin(), indices.end(), [&](int x, int y) { return heights[x] > heights[y]; }); vector<string> res(n); for (int i = 0; i < n; i++) { res[i] = names[indices[i]]; } return res; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public String[] sortPeople(String[] names, int[] heights) { intn= names.length; Integer[] indices = newInteger[n]; for (inti=0; i < n; i++) { indices[i] = i; } Arrays.sort(indices, (a, b) -> heights[b] - heights[a]); String[] res = newString[n]; for (inti=0; i < n; i++) { res[i] = names[indices[i]]; } return res; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9
classSolution: defsortPeople(self, names: List[str], heights: List[int]) -> List[str]: n = len(names) indices = list(range(n)) indices.sort(key=lambda x: heights[x], reverse=True) res = [] for i in indices: res.append(names[i]) return res
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcsortPeople(names []string, heights []int) []string { n := len(names) indices := make([]int, n) for i := 0; i < n; i++ { indices[i] = i } sort.Slice(indices, func(i, j int)bool { return heights[indices[j]] < heights[indices[i]] }) res := make([]string, n) for i := 0; i < n; i++ { res[i] = names[indices[i]] } return res }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10
var sortPeople = function(names, heights) { const n = names.length; const indices = Array.from({length: n}, (_, i) => i); indices.sort((a, b) => heights[b] - heights[a]); const res = newArray(n); for (let i = 0; i < n; i++) { res[i] = names[indices[i]]; } return res; };
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassSolution { publicstring[] SortPeople(string[] names, int[] heights) { int n = names.Length; int[] indices = newint[n]; for (int i = 0; i < n; i++) { indices[i] = i; } Array.Sort(indices, (a, b) => heights[b] - heights[a]); string[] res = newstring[n]; for (int i = 0; i < n; i++) { res[i] = names[indices[i]]; } return res; } }