2019-03-21-算法-进化(合并两个有序链表)
生活随笔
收集整理的這篇文章主要介紹了
2019-03-21-算法-进化(合并两个有序链表)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
將兩個有序鏈表合并為一個新的有序鏈表并返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4 輸出:1->1->2->3->4->4思路1:雙指針法
/*** 合并兩個有序鏈表(默認為升序)* 雙指針法* @param l1* @param l2* @return*/public ListNode mergeTwoLists(ListNode l1, ListNode l2) {if(l1 == null) {return l2;}if(l2 == null) {return l1;}ListNode head = new ListNode(-1);ListNode index = head;while(l1!=null && l2!=null) {if(l1.val>l2.val) {index.next = l2;l2=l2.next;}else {index.next = l1;l1 = l1.next;}index = index.next;}if(l1!=null) {while (l1!=null) {index.next = l1;l1 = l1.next;index = index.next;}}if(l2!=null) {while (l2!=null) {index.next = l2;l2 = l2.next;index = index.next;}}return head.next;}思路1代碼優化版(代碼短了,耗時反而增加了,應該是if else的判斷多了導致的)
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {if(l1 == null) {return l2;}if(l2 == null) {return l1;}ListNode head = new ListNode(-1);ListNode index = head;while(l1!=null || l2!=null) {if(l1 !=null && l2!=null) {if(l1.val>l2.val) {index.next = l2;l2=l2.next;}else {index.next = l1;l1 = l1.next;}}else if (l1 != null && l2==null) {index.next = l1;l1 = l1.next;}else if (l1 == null && l2!=null) {index.next = l2;l2=l2.next;}index = index.next;}return head.next;}思路1優化版,優化了時間
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {if(l1 == null) {return l2;}if(l2 == null) {return l1;}ListNode head = new ListNode(-1);ListNode index = head;while(l1!=null && l2!=null) {if(l1.val>l2.val) {index.next = l2;l2=l2.next;}else {index.next = l1;l1 = l1.next;}index = index.next;}//任一為空,直接鏈接另一個鏈表if(l1!=null) {index.next=l1;}else {index.next=l2;}return head.next;}總結
以上是生活随笔為你收集整理的2019-03-21-算法-进化(合并两个有序链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国科学院研发出可检测血浆 EVs 凝血
- 下一篇: 2019-03-22-算法-进化(回文链