[LeetCode Java Solution] – sort/ two pointers/ merge- Merge k Sorted Lists — 2015-05-20

[LeetCode Java Solution] – sort/ two pointers/ merge- Merge k Sorted Lists

Problem:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Method 1:

MergeSort. This is a very typical implementation for MergeSort by using array.

Code for method 1:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        return helper(lists, 0, lists.length-1);
    }
    
    public ListNode helper (ListNode[] lists, int l, int h){
        if (l < h){
             int mid = (l + h)/2;
             return merge(helper(lists, l, mid), helper(lists, mid+1, h));
        }
        return lists[l];
    }
    
    public ListNode merge(ListNode l1, ListNode l2){
        ListNode dummy = new ListNode(0);
        ListNode temp = dummy;
        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                temp.next = l1;
                temp = temp.next;
                l1 = l1.next;
            }else{
                temp.next = l2;
                temp = temp.next;
                l2 = l2.next;
            }
        }
        if (l1 != null){
            temp.next = l1;
        }
        if (l2 != null){
            temp.next = l2;
        }
        return dummy.next;
    }
}

Analysis for time complexity:

Suppose there are k lists, and there are n elements inside each list. The time complexity is O(nklogk).

Method 2:

Use heap. Suppose we have k lists, and for each list, there are at most n elements.

Maintain a list of k elements. And always remove the first element from the list. After removing an element, add the element after it to the heap.

Code for method 2:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(10, new Comparator<ListNode>(){
            public int compare (ListNode l1, ListNode l2){
                return l1.val - l2.val;
            }
        });
        
        for (int i = 0; i < lists.length; i++){
            ListNode temp = lists[i];
            if (temp != null){
                heap.offer(temp);
            }
        }
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        
        while (heap.size() != 0){
            ListNode n = heap.poll();
            cur.next = n;
            cur = cur.next;
            if (n.next != null){
                heap.offer(n.next);
            }
        }
        return dummy.next;
    }
}

Analysis for time complexity:

We have to insert at most k*n nodes, and for each node to be in order in the heap, we need log(k) time (“Bottom Up Insertion”). So total time complexity is also knlog(k).

[LeetCode Java Solution] – LinkedList – Swap nodes in pairs — 2015-05-16

[LeetCode Java Solution] – LinkedList – Swap nodes in pairs

Problem:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Method:

1. This is a singly linked list, so we have to keep two pointers. One is pre-temp, one is temp. And insert the node at temp.next between pre-temp and temp.

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pretemp = dummy;
        ListNode temp = head;
        
        
        while (temp != null && temp.next != null){
            // the following three lines of code are very important.
            pretemp.next = temp.next;
            temp.next = pretemp.next.next;
            pretemp.next.next = temp;
            
            pretemp = temp;
            temp = temp.next;
            
        }
        
        return dummy.next;
        
        
    }
}
[LeetCode] – LinkedList/Math – Add Two Numbers — 2015-05-06

[LeetCode] – LinkedList/Math – Add Two Numbers

Problems:

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Methods:

Add from the front to the end.

Details:

  • While condition better to be || instead of &&
  • Last step is to check for flag!!!

Code:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode c1 = l1;
        ListNode c2 = l2;
        ListNode c = dummy;
        int flag = 0;
        int digit = 0;
        while (c1 != null || c2 != null){
            if (c1 != null){
                digit += c1.val;
                c1 = c1.next;
            }
            if (c2 != null){
                digit += c2.val;
                c2 = c2.next;
            }
            if (flag != 0){
                digit += flag;
                flag = 0;
            }
            
            if (digit < 10){
                ListNode nNode = new ListNode(digit);
                c.next = nNode;
                c = c.next;
            }else{
                ListNode nNode = new ListNode(digit-10);
                c.next = nNode;
                c = c.next;
                flag = 1;
            }
            digit = 0;
        }
        if (flag == 1){
            ListNode nNode = new ListNode(1);
            c.next = nNode;
        }
        return dummy.next;
    }
}
[LeetCode] – Sort/ Two pointers/Merge – Merge Two Sorted List — 2015-04-30

[LeetCode] – Sort/ Two pointers/Merge – Merge Two Sorted List

Problem:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Method 1:

1. Use two pointers to move through the two lists. Compare and link the smaller one to the result list.

2. Use a dummy node to avoid choosing head for the new list.

3. To save space, do not have to create new node.

Code for method 1:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) return null;
   
        ListNode dummy = new ListNode(1);
        ListNode temp0 = dummy;
        ListNode temp1 = l1;
        ListNode temp2 = l2;
        
        while (temp1 != null && temp2 != null){
            if (temp1.val <= temp2.val){
              //  ListNode item = new ListNode(temp1.val);
              // to save space, do not have to create new object
                temp0.next = temp1;
                temp1 = temp1.next;
                temp0 = temp0.next;
            }else{
            //    ListNode item = new ListNode(temp2.val);
                temp0.next = temp2;
                temp2 = temp2.next;
                temp0 = temp0.next;
            }
        }
        if (temp1 != null){
            temp0.next = temp1;
        }
        if (temp2 != null){
            temp0.next = temp2;
        }
        return dummy.next;
    }
}