Leetcode刷题--数组序号转换

思路:可以先克隆一个一样的数组,然后排序,讲数组值作为key,序号作为value放入一个Map。

题解:

class Solution {
    public int[] arrayRankTransform(int[] arr) {
        int [] temp = arr.clone();
        HashMap<Integer,Integer> map = new HashMap();
        Arrays.sort(temp);
        int count = 1;
        int num = arr.length;
        for(int i = 0;i < num;i++){
            if(map.get(temp[i]) == null){
                map.put(temp[i],count);
                count++;
            }
        }
        for(int j = 0;j < num;j++){
            arr[j] = map.get(arr[j]);
        }
        return arr;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36428821/article/details/113407489