LeetCode 21. Merge Two Sorted Lists

一 题目

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

二 分析

求两个有序链表合成一个有序链 表。easy 级别。

2.1 使用list 排序

这是要排序。我先想到把了l1,l2放到一个list, 排序,再遍历list返回结果。

如果l1的长度为m,l2的长度为n, 遍历两遍。则时间复杂度为O(m+n);

//coner case
		if(l1 == null && l2== null){
			return null;
		}
		
		List<Integer> list =new ArrayList();
		
		while(l1!= null){			
			list.add(l1.val);
			l1 = l1.next;
		}
		while(l2 != null){
			list.add(l2.val);
			l2= l2.next;
		}
		Collections.sort(list);
		ListNode res= new ListNode(list.get(0));
		ListNode pre =res;
		for(int i=1;i<list.size();i++){
			ListNode node =new ListNode(list.get(i));
			pre.next= node;
			 pre = pre.next;
		}
		return res;

Runtime: 3 ms, faster than 20.46% of Java online submissions for Merge Two Sorted Lists.

Memory Usage: 38.3 MB, less than 19.53% of Java online submissions forMerge Two Sorted Lists.

使用一次遍历

每次取一个值(较小的),然后往后指向,再有另一个判断,直到取到末位。

我自己调试的时候,边界判断导致的异常是常见的。

另外,为了解决一开始head节点不赋值导致空指针异常,临时用一个值填充了下,最后返回结果再丢掉。

public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		//coner case:同时为空
		if(l1 == null && l2== null){
			return null;
		}	
        //临时用一个填充下
		ListNode res =new ListNode(l1==null?l2.val:l1.val);
		ListNode pre =res;
		while(l1!= null && l2 != null){		
			if(l1.val<=l2.val){
				pre.next  =new ListNode(l1.val);
				if(l1!= null){	
					l1 = l1.next;
				}
				pre = pre.next;
			}else {
				pre.next =new ListNode( l2.val);
				if(l2!= null){
					l2 = l2.next;
				}
				pre = pre.next;
			}
		}
		while(l1 != null){
			pre.next  =new ListNode(l1.val);
			l1 = l1.next;
			pre = pre.next;
		}
		while(l2 != null){
			pre.next  =new ListNode(l2.val);
			l2 = l2.next;
			pre = pre.next;
		}
		return res.next;        
    }

Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.

Memory Usage: 40.8 MB, less than 10.10% of Java online submissions forMerge Two Sorted Lists.

其实看到这个结果也不容易,思路是一致的,就是剪枝尝试了方式,

如果我开始用的((l1!= null && l2 != null&l1.val<=l2.val)||l2== null) 。那么就是1ms。

有时候算法你用对了,可是还是不一定是最快的,只能说优化的不够好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值