1. 程式人生 > 其它 >LG P3803 【模板】多項式乘法(FFT)

LG P3803 【模板】多項式乘法(FFT)

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

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]

Constraints:

  • The number of nodes in both lists is in the range[0, 50].
  • -100 <= Node.val <= 100
  • Bothl1andl2are sorted innon-decreasingorder.

合併兩個有序連結串列。

給兩個有序連結串列,請將兩個連結串列merge,並且輸出的連結串列也是有序的。

時間O(m + n),兩個連結串列的長度

空間O(1)

思路:

用一個dummy node去遍歷兩個連結串列,然後比較兩者的node.val。

解法類似歸併排序的merge過程

merge K個連結串列

類似題:

23題影子題148,做法幾乎一模一樣

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null&&l2==null){
            return null;
        }
        ListNode p1=l1;
        ListNode p2=l2;
        ListNode p3=new ListNode(0);
        ListNode cur=p3;
        while(p1!=null && p2!=null){
            if(p1.val<p2.val){
                cur.next=p1;
                p1=p1.next;          
            }else{
                cur.next=p2;
                p2=p2.next;
            }
             cur=cur.next;
        }
      while(p1!=null){
          cur.next=p1;
          cur=cur.next;
          p1=p1.next;
      }
      while(p2!=null){
          cur.next=p2;
          cur=cur.next;
          p2=p2.next;
      }
      return p3.next;
    }
}