Algorithm之路二十一:Merge Two Sorted Lists
来源:互联网 发布:用手指舒服吗 知乎 编辑:程序博客网 时间:2024/06/09 15:10
题目:
给出两个排好序的列表,将两个列表按照组合到一起,并且按照从小到大的顺序排好序。
举例:Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
代码:
public class Merge_Two_Sorted_Lists {public static class ListNode{int val;ListNode next;ListNode(int x){val = x;}}public static ListNode mergeTwoLists(ListNode l1, ListNode l2){ListNode temp = new ListNode(0);ListNode temp1 = temp;while(l1 != null || l2 != null){if(l1 != null && l2 != null){if(l1.val <= l2.val){temp.next = new ListNode(l1.val);temp = temp.next;l1 = l1.next;}else{temp.next = new ListNode(l2.val);temp = temp.next;l2 = l2.next;}}if(l1 == null){while(l2 != null){temp.next = new ListNode(l2.val);temp = temp.next;l2 = l2.next;}}if(l2 == null){while(l1 != null){temp.next = new ListNode(l1.val);temp = temp.next;l1 = l1.next;}}}temp1 = temp1.next;return temp1; }public static void main(String[] args){ListNode l1 = null;ListNode l2 = new ListNode(1);l2.next = new ListNode(3);l2.next.next = new ListNode(4);System.out.println(mergeTwoLists(l1,l2).toString());}}
时间复杂度:
O(m+n),m和n分别是两个输入链表的长度。
空间复杂度:
O(m+n)。
阅读全文
0 0
- Algorithm之路二十一:Merge Two Sorted Lists
- Algorithm之路二十三:Merge k Sorted Lists
- 【Leetcode Algorithm】Merge Two Sorted Lists
- 每日算法之二十一:Merge k Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- 使用Spring Security实现权限管理
- 七夕节
- 机器学习之线性回归的最小二乘法求解
- 大商创 pc网页跳转对应移动端网页
- 常见算法及问题场景——图
- Algorithm之路二十一:Merge Two Sorted Lists
- jdk下载
- JavaScript~对象的复制
- 单机运行 spark-shell错误
- 常用的正则表达式
- mysql 存emoji表情 utf8mb4
- Part1-HttpClient快速入门案例
- Spring MVC概述
- RxJava和RxAndroid