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 Mapm = 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条)