“月度”LeetCode刷题之2023-02
今年的计划是用 Go 刷 150道
LeetCode21. 合并两个有序链表
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
dummyHead := &ListNode{}
p := dummyHead
for list1 != nil && list2 != nil {
if list1.Val >= list2.Val {
p.Next = list2
list2 = list2.Next
} else {
p.Next = list1
list1 = list1.Next
}
p = p.Next
}
if list1 != nil {
p.Next = list1
}
if list2 != nil {
p.Next = list2
}
return dummyHead.Next
}
LeetCode 86. 分隔链表
func partition(head *ListNode, x int) *ListNode {
small := &ListNode{}
smallHead := small
large := &ListNode{}
largeHead := large
for head != nil {
if head.Val < x {
small.Next = head
small = small.Next
} else {
large.Next = head
large = large.Next
}
head = head.Next;
}
large.Next = nil
small.Next = largeHead.Next
return smallHead.Next
}
LeetCode 83. 删除排序链表中的重复元素
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil {
return nil
}
cur := head
for cur.Next != nil {
if cur.Val == cur.Next.Val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return head
}
LeetCode 27. 移除元素
func removeElement(nums []int, val int) int {
left := 0
for _,v := range nums {
if(v != val) {
nums[left] = v
left++
}
}
return left
}