LeetCode知识点总结 - 1122

LeetCode 1122. Relative Sort Array

考点难度
SortingEasy
题目

Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.

思路

把所有arr2中的数字存到map里。对于arr1里的每个数,如果在arr2中出现过就更新map,如果没出现过,加到result的结尾。根据arr2的顺序,按照每个数字出现的次数把result的第一部分填满。sort result的后半部分。

答案
public int[] relativeSortArray(int[] arr1, int[] arr2) {
        //create map for counting numbers in arr2. Initialize everything with zeroes
        Map<Integer, Integer> m = new HashMap();
        for (int num : arr2) {
            m.put(num, 0);
        }
        int last = arr1.length - 1;
        int[] res = new int[arr1.length];
        //iterate over arr1  and count numbers of time this element is in arr1
        for (int num : arr1) {
            //if number is from arr2 - increment count
            if (m.containsKey(num))
                m.put(num, m.get(num) + 1);
            //otherwise add element to the end of res and decrement the pointer
            else {
                res[last--] = num;
            }
        }
        //iterate over arr2, fill elements in res based on it's count 
        int p = 0;
        for (int num : arr2) {
            int c = m.get(num);
            for (int i = 0; i < c; i++) {
                res[p++] = num;
            }
        }
        //now sort the leftovers - p points to the first element in series of those from arr2 that are not in arr1 
        Arrays.sort(res, p, res.length);
        return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值