Java [leetcode 23]Merge k Sorted Lists

题目描述:

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

解题思路:

分治方法。将K个List不断地分解为前半部分和后半部分。分别进行两个List的合并。最后将合并的结果合并起来。

代码如下:

/**

 * 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.length == 0)

			return null;

		return divide(lists, 0, lists.length - 1);

	}

	

	public ListNode divide(ListNode[] l1, int left, int right) {

		if(left < right){

			int mid = (left + right) / 2;

			return mergeTwoLists(divide(l1, left, mid), divide(l1, mid + 1, right));

		}

		return l1[left];

	}



	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

		ListNode list = new ListNode(0);

		ListNode tmp = list;

		while (l1 != null || l2 != null) {

			if (l1 == null) {

				tmp.next = new ListNode(l2.val);

				l2 = l2.next;

			} else if (l2 == null) {

				tmp.next = new ListNode(l1.val);

				l1 = l1.next;

			} else {

				if (l1.val < l2.val) {

					tmp.next = new ListNode(l1.val);

					l1 = l1.next;

				} else {

					tmp.next = new ListNode(l2.val);

					l2 = l2.next;

				}

			}

			tmp = tmp.next;

		}

		return list.next;

	}

}

 

你可能感兴趣的:(LeetCode)