|
| 1 | +package com.fishercoder.solutions.fourththousand; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +public class _3237 { |
| 7 | + public static class Solution1 { |
| 8 | + /** |
| 9 | + * My completely original solution, very natural to think of doubly linked list + hashmap. |
| 10 | + */ |
| 11 | + public int[] simulationResult(int[] windows, int[] queries) { |
| 12 | + Map<Integer, DoublyLinkedListNode> map = new HashMap<>(); |
| 13 | + DoublyLinkedListNode pre = buildList(windows, map); |
| 14 | + for (int q : queries) { |
| 15 | + moveToHead(q, pre, map); |
| 16 | + } |
| 17 | + return backToArray(pre, windows.length); |
| 18 | + } |
| 19 | + |
| 20 | + private int[] backToArray(DoublyLinkedListNode pre, int length) { |
| 21 | + DoublyLinkedListNode tmp = pre; |
| 22 | + int[] ans = new int[length]; |
| 23 | + for (int i = 0; i < length; i++) { |
| 24 | + ans[i] = tmp.next.val; |
| 25 | + tmp = tmp.next; |
| 26 | + } |
| 27 | + return ans; |
| 28 | + } |
| 29 | + |
| 30 | + private void moveToHead(int q, DoublyLinkedListNode headPrev, Map<Integer, DoublyLinkedListNode> map) { |
| 31 | + DoublyLinkedListNode node = map.get(q); |
| 32 | + //if this window is already at the head, then we don't need to do anything |
| 33 | + if (headPrev.next == node) { |
| 34 | + return; |
| 35 | + } |
| 36 | + //get this node's next and prev pointers |
| 37 | + DoublyLinkedListNode next = node.next; |
| 38 | + DoublyLinkedListNode prev = node.prev; |
| 39 | + //connect it's next to its previous' next, essentially cutting the current node out of the chain |
| 40 | + prev.next = next; |
| 41 | + //in case this is tail, we don't need to re-assign its next pointer |
| 42 | + if (next != null) { |
| 43 | + next.prev = prev; |
| 44 | + } |
| 45 | + DoublyLinkedListNode oldHead = headPrev.next; |
| 46 | + headPrev.next = node; |
| 47 | + node.next = oldHead; |
| 48 | + oldHead.prev = node; |
| 49 | + } |
| 50 | + |
| 51 | + private DoublyLinkedListNode buildList(int[] windows, Map<Integer, DoublyLinkedListNode> map) { |
| 52 | + DoublyLinkedListNode pre = new DoublyLinkedListNode(-1); |
| 53 | + DoublyLinkedListNode tmp = pre; |
| 54 | + for (int i = 0; i < windows.length; i++) { |
| 55 | + DoublyLinkedListNode next = new DoublyLinkedListNode(windows[i]); |
| 56 | + next.prev = tmp; |
| 57 | + tmp.next = next; |
| 58 | + map.put(windows[i], next); |
| 59 | + tmp = tmp.next; |
| 60 | + } |
| 61 | + return pre; |
| 62 | + } |
| 63 | + |
| 64 | + public static class DoublyLinkedListNode { |
| 65 | + DoublyLinkedListNode prev; |
| 66 | + DoublyLinkedListNode next; |
| 67 | + int val; |
| 68 | + |
| 69 | + public DoublyLinkedListNode(int val) { |
| 70 | + this.val = val; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments