Skip to content

Latest commit

 

History

History
120 lines (100 loc) · 2.06 KB

File metadata and controls

120 lines (100 loc) · 2.06 KB
title subtitle date lastmod draft author authorLink description license images tags categories featuredImage featuredImagePreview hiddenFromHomePage hiddenFromSearch twemoji lightgallery ruby fraction fontawesome linkToMarkdown rssFullText toc code math mapbox share comment library seo
0021. Merge Two Sorted Lists
2023-11-05 21:30:00 +0800
2023-11-05 21:30:00 +0800
false
Kimi.Tsai
0021.Merge-Two-Sorted-Lists
LeetCode
Go
Easy/Medium/Hard
Merge Two Sorted Lists
LeetCode
false
false
false
true
true
true
true
false
false
enable auto
true
true
copy maxShownLines
true
200
enable
enable
true
enable
true
css js
images

題目

題目大意

解題思路

Big O

時間複雜 : O( log n) 空間複雜 : O(1)

來源

解答

https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0021.Merge-Two-Sorted-Lists/main.go

package mergetwosortedlists

type ListNode struct {
	Val  int
	Next *ListNode
}

// 時間複雜 O(log n), 空間複雜 O(1)
func MergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	head := &ListNode{Next: nil}
	cur := head

	for list1 != nil && list2 != nil {
		if list1.Val < list2.Val {
			cur.Next = list1
			list1 = list1.Next
		} else {
			cur.Next = list2
			list2 = list2.Next
		}
		cur = cur.Next
	}

	if list1 != nil {
		cur.Next = list1
	}
	if list2 != nil {
		cur.Next = list2
	}
	return head.Next
}

Benchmark