3ms java solution using a hashmap


  • 0
    A
    public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode p = head;
            HashMap<Integer, ListNode> map = new HashMap<>();
            int i = 1;
            for (i = 1; p != null; i++, p = p.next) {
                map.put(i, p);
            }
            if (n == i - 1) return (map.get(i - n)).next;
            ListNode temp = map.get(i - n - 1);
            temp.next = temp.next.next;
            return head;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.