LeetCode热题100道-Day02

59 阅读1分钟

LeetCode热题100道-Day02

21. 合并两个有序链表

  • 两个指针分别指向两个链表,然后两个指针指向的值进行比较,选出较小的值,然后该指针向后移一位,循环这样操作即可得出有序链表
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
    res := &ListNode{}
    p := res
    for list1!=nil && list2!=nil {
        if list1.Val<list2.Val {
            p.Next = list1
            list1 = list1.Next
        } else {
            p.Next = list2
            list2 = list2.Next
        }
        p = p.Next
    }
    if list1!=nil {
        p.Next = list1
    }
    if list2!=nil {
        p.Next = list2
    }    
    return res.Next
}

46. 全排列

  • 递归遍历
var res [][]int
var list []int
func permute(nums []int) [][]int {
    res = [][]int{}
    used := make([]bool, len(nums))
    list = []int{}
    tra(nums, used)
    return res
}
func tra(nums []int, X []bool) {
    if len(list)==len(nums) {
        t := make([]int, len(list))
        copy(t, list)
        res = append(res, t)
        return
    }
    for i:=0; i<len(nums); i++ {
        if X[i] {
            continue
        }
        list = append(list, nums[i])
        X[i] = true
        tra(nums, X)
        X[i] = false
        list = list[:len(list)-1]
    }
}

206. 反转链表

  • 定义指针c为当前点, p表示当前点的前一位, n为当前点的后一位,遍历调整当前点的Next即可
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    var p *ListNode
    c := head
    for c!=nil {
        n := c.Next
        c.Next = p
        p = c
        c = n    
    }
    return p
}

226. 翻转二叉树

  • 后序遍历的时候,交换左右节点
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
    tra(root)
    return root
}
func tra(root *TreeNode) {
    if root==nil {
        return
    }
    tra(root.Left)
    tra(root.Right)
    temp := root.Left
    root.Left = root.Right
    root.Right = temp
}

234. 回文链表

  • 将链表转成数组,然后头尾两指针同时遍历判断
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func isPalindrome(head *ListNode) bool {
    list := make([]int, 0)
    for head!=nil {
        list = append(list, head.Val)
        head = head.Next
    }
    i := 0
    j := len(list)-1
    for i<j {
        if list[i]!=list[j] {
            return false
        }
        i++
        j--
    }
    return true
}