1122. Relative Sort Array

1122. Relative Sort Array

class Solution {
    	public int[] relativeSortArray(int[] arr1, int[] arr2) {
		HashMap h = new HashMap();
		for (int i = 0; i < arr2.length; i++) {
			h.put(i, arr2[i]);
		}
		// queue to keep the new list in ascending order
		PriorityQueue rem = new PriorityQueue();
		int existing = 0;
		for (int i = 0; i < arr1.length; i++) {
			if (null != getKeyFromValue(h, arr1[i])) {
				arr1[i] = getKeyFromValue(h, arr1[i]);
				existing++;
			} else {
				rem.add(arr1[i]);
               arr1[i] = Integer.MAX_VALUE;

			}
		}
		Arrays.sort(arr1);
		for (int i = 0; i < existing; i++) {
			arr1[i] = h.get(arr1[i]);
		}
		for (int i = existing; i < arr1.length; i++) {
			arr1[i] = rem.poll();
		}
		return arr1;
	}

	public static Integer getKeyFromValue(HashMap hm, int value) {
		for (Integer o : hm.keySet()) {
			if (((Integer) hm.get(o)).intValue() == value) {
				return o;
			}
		}
		return null;
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s