classSolution: defarrayRankTransform(self, arr: List[int]) -> List[int]: ranks = {v: i for i, v inenumerate(sorted(set(arr)), 1)} return [ranks[v] for v in arr]
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicint[] arrayRankTransform(int[] arr) { int[] sortedArr = newint[arr.length]; System.arraycopy(arr, 0, sortedArr, 0, arr.length); Arrays.sort(sortedArr); Map<Integer, Integer> ranks = newHashMap<Integer, Integer>(); int[] ans = newint[arr.length]; for (int a : sortedArr) { if (!ranks.containsKey(a)) { ranks.put(a, ranks.size() + 1); } } for (inti=0; i < arr.length; i++) { ans[i] = ranks.get(arr[i]); } return ans; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution { publicint[] ArrayRankTransform(int[] arr) { int[] sortedArr = newint[arr.Length]; Array.Copy(arr, 0, sortedArr, 0, arr.Length); Array.Sort(sortedArr); Dictionary<int, int> ranks = new Dictionary<int, int>(); int[] ans = newint[arr.Length]; foreach (int a in sortedArr) { ranks.TryAdd(a, ranks.Count + 1); } for (int i = 0; i < arr.Length; i++) { ans[i] = ranks[arr[i]]; } return ans; } }
var arrayRankTransform = function(arr) { const sortedArr = newArray(arr.length).fill(0); sortedArr.splice(0, arr.length, ...arr); sortedArr.sort((a, b) => a - b); const ranks = newMap(); const ans = newArray(arr.length).fill(0); for (const a of sortedArr) { if (!ranks.has(a)) { ranks.set(a, ranks.size + 1); } } for (let i = 0; i < arr.length; i++) { ans[i] = ranks.get(arr[i]); } return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcarrayRankTransform(arr []int) []int { a := append([]int{}, arr...) sort.Ints(a) ranks := map[int]int{} for _, v := range a { if _, ok := ranks[v]; !ok { ranks[v] = len(ranks) + 1 } } for i, v := range arr { arr[i] = ranks[v] } return arr }