203. 移除链表元素 Remove Linked-list Elements
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50
代码:
package main import "fmt" type ListNode struct { Val int Next *ListNode } func removeElements(head *ListNode, val int) *ListNode { top := &ListNode{Val: 0} top.Next = head pre := top temp := head for temp != nil { if temp.Val == val { pre.Next = temp.Next } else { pre = temp } temp = temp.Next } return top.Next } func createLinkedList(nums []int) *ListNode { if len(nums) == 0 { return nil } head := &ListNode{Val: nums[0]} cur := head for i := 1; i < len(nums); i++ { cur.Next = &ListNode{Val: nums[i]} cur = cur.Next } return head } func printLinkedList(head *ListNode) { cur := head for cur != nil { fmt.Print(cur.Val, "->") cur = cur.Next } fmt.Println("nil") } func main() { nums := []int{1, 2, 6, 3, 4, 5, 6} head := createLinkedList(nums) printLinkedList(head) head = removeElements(head, 6) printLinkedList(head) nums2 := []int{} head = createLinkedList(nums2) printLinkedList(head) head = removeElements(head, 1) printLinkedList(head) nums3 := []int{7, 7, 7, 7} head = createLinkedList(nums3) printLinkedList(head) head = removeElements(head, 7) printLinkedList(head) }
输出:
1->2->6->3->4->5->6->nil
1->2->3->4->5->nil
nil
nil
7->7->7->7->nil
nil
递归法:
package main import "fmt" type ListNode struct { Val int Next *ListNode } func removeElements(head *ListNode, val int) *ListNode { if head == nil { return nil } head.Next = removeElements(head.Next, val) if head.Val == val { return head.Next } return head } func createLinkedList(nums []int) *ListNode { if len(nums) == 0 { return nil } head := &ListNode{Val: nums[0]} cur := head for i := 1; i < len(nums); i++ { cur.Next = &ListNode{Val: nums[i]} cur = cur.Next } return head } func printLinkedList(head *ListNode) { cur := head for cur != nil { fmt.Print(cur.Val, "->") cur = cur.Next } fmt.Println("nil") } func main() { nums := []int{1, 2, 6, 3, 4, 5, 6} head := createLinkedList(nums) printLinkedList(head) head = removeElements(head, 6) printLinkedList(head) }
204. 计数质数 Count Primes
给定整数 n
,返回 所有小于非负整数 n
的质数的数量 。
示例 1:
输入:n = 10
输出:4
解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
示例 2:
输入:n = 0
输出:0
示例 3:
输入:n = 1
输出:0
提示:
0 <= n <= 5 * 10^6
代码:
package main import ( "fmt" "math" ) func countPrimes(n int) int { if n <= 2 { return 0 } isPrime := make([]bool, n) for i := 0; i < n; i++ { isPrime[i] = true } isPrime[0] = false isPrime[1] = false for i := 2; i <= int(math.Sqrt(float64(n))); i++ { if isPrime[i] { for j := i * i; j < n; j += i { isPrime[j] = false } } } count := 0 for i := 0; i < n; i++ { if isPrime[i] { count++ } } return count } func main() { fmt.Println(countPrimes(10)) fmt.Println(countPrimes(0)) fmt.Println(countPrimes(1)) }
输出:
4
0
0