LeetCode 1331. Rank Transform of an Array
考点 | 难度 |
---|---|
Sorting | Easy |
题目
Given an array of integers arr
, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
Rank is an integer starting from 1.
The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.
思路
先对所有数字排序,按照顺序加到map里面并且保存这个数排序后的位置(map.size() + 1
)。用这个位置代替arr
里的每一个数。
答案
public int[] arrayRankTransform(int[] arr) {
int len = arr.length;
int[] clone = Arrays.copyOf(arr, len);
Arrays.sort(clone);
Map<Integer,Integer> map = new HashMap<>();
for(int i=0; i<len; i++){
if(!map.containsKey(clone[i])){
map.put(clone[i], map.size()+1);
}
}
for(int i=0; i<len; i++){
arr[i] = map.get(arr[i]);
}
return arr;
}