索引 1. Go 1.1. 核心数据类型 1.1.1. 整数和浮点数1 2 3 4 5 6 7 8 9 var x int = 10 y := -5 var big int64 = 1 << 62 pi := 3.14159 a := 5.0 b := int (a)
极值1 2 3 4 5 import "math" const MaxInt = math.MaxIntconst MinInt = math.MinIntconst MaxFloat64 = math.MaxFloat64
1.1.2. 字符串 & runeGo 的字符串是不可变的字节切片,处理包含中文或特殊字符的字符串时,必须使用 rune1 2 3 4 5 6 7 8 9 s := "Hello 世界" len (s) len ([]rune (s)) var ch byte = 'A' var r rune = '世' s = s + "!"
1.1.3. 变量交换 1.2. 核心数据结构 1.2.1. 切片 动态数组 1.2.1.1. 创建1 2 3 4 5 6 7 8 nums := []int {1 , 2 , 3 } ans := make ([]int , 0 ) grid := make ([][]int , n) for i := range grid { grid[i] = make ([]int , m) }
1.2.1.2. 访问与切片切片是浅拷贝 ,修改子切片会影响原切片1 2 3 4 val := nums[0 ] sub := nums[1 :3 ] copySub := make ([]int , len (sub)) copy (copySub, sub)
1.2.1.3. 常用操作1 2 3 4 5 nums = append (nums, 4 ) nums = append (nums, 5 , 6 ) n := len (nums) c := cap (nums)
1.2.2. map 映射 哈希表无序键值对
1.2.2.1. 创建 操作1 2 3 4 5 6 7 m := make (map [string ]int ) m["age" ] = 18 dict := map [string ]int { "a" : 1 , "b" : 2 , }
map[keyType]valueType 在初始化的时候使用keyType: valueType,
1.2.2.2. Key Check1 2 3 4 5 6 val, ok := map ["a" ] if val, ok := map ["a" ]; ok { pass }
1.2.2.3. 删除 遍历1 2 3 4 5 6 7 delete (map , "a" )for k, v := range m { fmt.Println(k, v) }
1.2.3. 控制流 1.2.3.1. 条件判断 if1 2 3 4 5 6 7 8 if x := 10 ; x > 5 { fmt.Println(x) } else if x == 5 { pass } else { pass }
1.2.3.2. 循环 for有且仅有 for1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 for i := 0 ; i < 5 ; i++ { pass } i := 0 for i < 5 { i++ } for { break } for i, v := range nums { ... } for i := range nums { ... } for _, v := range nums { ... } for k, v := range myMap { ... } for i, ch := range str { ... }
1.2.3.3. switch默认不需要break1 2 3 4 5 6 7 8 switch score / 10 {case 10 , 9 : fmt.Println("A" ) case 8 : fmt.Println("B" ) default : fmt.Println("C" ) }
1.3. 常用内置库与函数 1.3.1. 排序 sort1 2 3 4 5 6 7 8 9 10 11 12 import "sort" nums := []int {3 , 1 , 2 } sort.Ints(nums) sort.Strings(strList) sort.Slice(nums, func (i, j int ) bool { return abs(nums[i]) > abs(nums[j]) })
1.3.2. 数学 mathGo 的 math 库主要针对 float64。对于 int,Go 1.21 引入了内置 min/max1 2 3 4 5 6 7 8 9 import "math" m := max(1 , 5 ) n := min(10 , 2 ) f := math.Abs(-5.2 ) p := math.Pow(2 , 10 ) sq := math.Sqrt(16 ) func abs (x int ) int { if x < 0 { return -x }; return x }
1.3.3. 字符串处理 strings / strconv1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import ( "strings" "strconv" ) arr := strings.Split("a,b,c" , "," ) s := strings.Join(arr, "-" ) idx := strings.Index("hello" , "e" ) cnt := strings.Count("banana" , "a" ) has := strings.Contains("hello" , "he" ) num, err := strconv.Atoi("123" ) str := strconv.Itoa(123 )
1.4. 常见算法模板实现 1.4.1. stack 栈没有内置栈1 2 3 4 5 6 7 8 9 10 11 12 13 14 stack := []int {} stack = append (stack, 1 ) top := stack[len (stack)-1 ] val := stack[len (stack)-1 ] stack = stack[:len (stack)-1 ] isEmpty := len (stack) == 0
1.4.2. Queue 队列用切片模拟,出队操作如果是 nums = nums[1:] 可能会导致内存泄漏(底层数组未释放),通常可以忽略1 2 3 4 5 6 7 8 9 10 11 queue := []int {} queue = append (queue, 1 ) val := queue[0 ] queue = queue[1 :] isEmpty := len (queue) == 0
1.4.3. Set 集合Go 没有 set 类型,使用 map[key]bool 或 map[key]struct{} 模拟1 2 3 4 5 6 7 8 9 10 set := make (map [int ]struct {}) set[1 ] = struct {}{} if _, ok := set[1 ]; ok { ... }delete (set, 1 )
1.4.4. ListNode 链表1 2 3 4 5 6 7 8 type ListNode struct { Val int Next *ListNode } dummy := &ListNode{Next: head} cur := dummy
1.4.5. TreeNode 二叉树1 2 3 4 5 type TreeNode struct { Val int Left *TreeNode Right *TreeNode }
1.4.6. 优先队列 / 堆 Priority Queue需要实现 heap.Interface 接口1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import "container/heap" type IntHeap []int func (h IntHeap) Len() int { return len (h) }func (h IntHeap) Less(i, j int ) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int ) { h[i], h[j] = h[j], h[i] }func (h *IntHeap) Push(x interface {}) { *h = append (*h, x.(int )) } func (h *IntHeap) Pop() interface {} { old := *h n := len (old) x := old[n-1 ] *h = old[0 : n-1 ] return x } func main () { h := &IntHeap{2 , 1 , 5 } heap.Init(h) heap.Push(h, 3 ) minVal := heap.Pop(h).(int ) }
1.4.7. 位运算1 2 3 4 5 6 x & y x | y x ^ y x &^ y x << n x >> n
1.4.8. 输入输出1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import ( "bufio" "fmt" "os" ) func main () { in := bufio.NewReader(os.Stdin) out := bufio.NewWriter(os.Stdout) defer out.Flush() var n int fmt.Fscan(in, &n) fmt.Fprintln(out, n) }
1.4.9. 并查集 Union-Find (DSU)处理连通性问题1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 parent := make ([]int , n) for i := range parent { parent[i] = i } var find func (int ) int find = func (x int ) int { if parent[x] != x { parent[x] = find(parent[x]) } return parent[x] } union := func (from, to int ) { p1, p2 := find(from), find(to) if p1 != p2 { parent[p1] = p2 } }
1.4.10. 图的存储 (邻接表)Go 通常用 [][]int 表示图1 2 3 4 5 6 7 graph := make ([][]int , n) for _, e := range edges { u, v := e[0 ], e[1 ] graph[u] = append (graph[u], v) graph[v] = append (graph[v], u) }
1.4.11. 字典树 Trie (前缀树)前缀问题1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 type Trie struct { children [26 ]*Trie isEnd bool } func (t *Trie) Insert(word string ) { node := t for _, ch := range word { idx := ch - 'a' if node.children[idx] == nil { node.children[idx] = &Trie{} } node = node.children[idx] } node.isEnd = true }
// To be continued
1.5. 常用算法技巧 1.5.1. 二分查找除了手写 left <= right,Go 标准库提供了非常强大的二分模板1 2 3 4 5 6 7 8 9 10 l, r := 0 , len (nums) for l < r { mid := int (uint (l+r) >> 1 ) if nums[mid] >= target { r = mid } else { l = mid + 1 } }
标准库 sort.Search sort.Search(n, f) 返回[0, n)中第一个满足 f(i) == true 的索引 i。如果都不满足,返回 n1 2 3 4 5 6 7 8 9 import "sort" idx := sort.Search(len (nums), func (i int ) bool { return nums[i] >= target }) if idx < len (nums) && nums[idx] == target { fmt.Println("Found at" , idx) }
1.5.2. 网格遍历 (方向数组)DFS/BFS 搜索二维网格1 2 3 4 5 6 7 8 9 dirs := []struct { x, y int }{ {-1 , 0 }, {1 , 0 }, {0 , -1 }, {0 , 1 } } for _, d := range dirs { nx, ny := x + d.x, y + d.y if nx >= 0 && nx < n && ny >= 0 && ny < m { } }
2. Python 部分 2.1. 核心数据类型 2.1.1. 整数 (int)x = 10, y = -5
2.1.2. 浮点数 (float)pi = 3.14
2.1.3. 布尔值 (bool)flag = True, flag = False
2.1.4. 字符串 (str)s = “hello world”
a, b = b, a 交换变量
2.2. 核心数据结构 2.2.1. 列表 (List) 2.2.1.1. 创建1 2 3 nums = [1 , 2 , 3 , 4 ] ans = []
2.2.1.2. 访问1 2 3 first = nums[0 ] last = nums[-1 ]
2.2.1.3. 切片创建子列表,语法 [start:stop:step]1 2 3 4 copy = nums[:] reverse = nums[::-1 ]
2.2.1.4. 列表的常用函数和操作1 2 3 4 5 len (nums) sum (nums) min (nums) / max (nums) sorted (nums) value in nums
2.2.1.5. 列表的常用方法1 2 3 4 5 nums.append(value) nums.pop(index) nums.sort() nums.reverse() nums.index(value)
2.2.2. 字典 (Dictionary / Hash Map)字典是无序的键值对 (key: value) 集合。它通过哈希表实现,查找、插入、删除的平均时间复杂度为 O(1)
2.2.2.1. 创建1 2 lookup = {'name' : 'Alice' , 'id' : 123 } empty_dict = {}
2.2.2.2. 操作1 2 3 4 5 6 7 8 9 10 11 12 name = lookup['name' ] lookup['id' ] = 456 'id' in lookup del lookup['id' ] for key in lookup.keys() for value in lookup.values() for key, value in lookup.items()
2.2.3. 集合 (Set)集合是无序、不重复的元素集合。其底层也是哈希表,因此检查一个元素是否存在 的速度极快 (O(1))
2.2.3.1. 创建1 2 3 4 unique_nums = {1 , 2 , 3 } empty_set = set () from_list = set ([1 , 2 , 2 , 3 , 1 ])
2.2.3.2. 操作1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 unique_nums.add(4 ) unique_nums.remove(3 ) 3 in unique_nums set1 = {1 , 2 , 3 } set2 = {3 , 4 , 5 } intersection = set1 & set2 union = set1 | set2 difference = set1 - set2
2.2.4. 字符串 (String)不可变的文本序列
2.2.4.1. 操作切片和索引 与列表 完全相同1 2 3 4 5 6 new_str = str1 + str2 ' ' .join(['111' , '222' , '333' ]) "a,b,c" .split(',' )
2.3. 控制流与逻辑 2.3.1. 条件判断 (if/elif/else)1 2 3 4 5 6 if score > 90 : grade = 'A' elif score > 80 : grade = 'B' else : grade = 'C'
三元运算符 (Ternary Operator) : result = “Even” if num % 2 == 0 else “Odd”
2.3.2. 循环 2.3.2.1. for循环1 2 3 4 5 6 7 8 9 10 for num in numbers: print (num) for i in range (5 ): print (i) for index, value in enumerate (numbers): print (f"Index: {index} , Value: {value} " )
2.3.2.2. while 循环1 2 3 4 count = 5 while count > 0 : print (count) count -= 1
2.3.3. 函数1 2 3 4 5 6 7 8 9 def solve (parameter1, parameter2 ): result = 0 return result
2.4. 通用内置函数 2.4.1. len(obj)1 2 3 length = len ([1 , 5 , 9 ]) str_len = len ("hello" ) dict_len = len ({'a' : 1 , 'b' : 2 })
2.4.2. sum(iterable)1 2 total = sum ([10 , 20 , 30 ])
2.4.3. min(iterable) / max(iterable)1 2 3 4 min_val = min ([3 , 1 , 9 , 2 ]) max_val = max ([3 , 1 , 9 , 2 ]) min_char = min ("database" )
2.4.4. sorted(iterable)1 2 3 4 5 6 7 nums = [3 , 1 , 4 , 2 ] new_sorted_list = sorted (nums) sorted_chars = sorted ("bca" )
2.4.5. abs(x) 2.4.6. range(start, stop, step)1 2 3 4 5 6 7 8 9 10 11 for i in range (3 ): print (i) for i in range (1 , 4 ): print (i) for i in range (0 , 5 , 2 ): print (i)
2.4.7. 类型转换函数 2.4.7.1. int(x) 2.4.7.2. str(obj) 2.4.7.3. list(iterable) 2.4.7.4. set(iterable)1 new_set=set ([1 , 2 , 2 , 3 ])
2.4.8. enumerate(iterable)1 2 3 4 5 6 7 letters = ['a' , 'b' , 'c' ] for index, value in enumerate (letters): print (f"Index: {index} , Value: {value} " )
2.4.9. zip()1 2 3 4 5 6 7 names = ['Alice' , 'Bob' ] scores = [95 , 88 ] for name, score in zip (names, scores): print (f"{name} : {score} " )
2.4.10. map(function, iterable)1 2 3 4 5 6 7 8 str_nums = ["1" , "2" , "3" ] int_nums = list (map (int , str_nums)) line = "10 20 30" nums = list (map (int , line.split()))
2.5. 核心数据类型方法 2.5.1. 字符串 (str) 2.5.1.1. str.split(sep)1 2 3 4 5 s = "hello world" words = s.split(' ' ) csv = "a,b,c" items = csv.split(',' )
2.5.1.2. sep.join(list)1 2 3 4 5 words = ['hello' , 'world' ] s = " " .join(words) chars = ['p' , 'y' ] result = "-" .join(chars)
2.5.1.3. str.find(sub)1 2 3 4 s = "banana" index1 = s.find('na' ) index2 = s.find('z' )
2.5.1.4. str.count(sub)1 2 s = "banana" count = s.count('a' )
2.5.1.5. str.strip()1 2 s = " hello " clean_s = s.strip()
2.5.1.6. str.isdigit()1 2 3 4 s1 = "123" s2 = "a123" print (s1.isdigit()) print (s2.isdigit())
2.5.2. 列表 (list) 2.5.2.1. list.index(x[, start[, end]])1 2 3 4 aList = [123 , 'xyz' , 'runoob' , 'abc' ] index1 = aList.index( 'xyz' ) index2 = aList.index( 'runoob' , 1 , 3 )
2.5.2.2. list.append(x)1 2 nums = [1 , 2 ] nums.append(3 )
2.5.2.3. list.pop(i)时间复杂度为O(n),list模拟队列效率很低1 2 3 4 nums = [10 , 20 , 30 ] last = nums.pop() first = nums.pop(0 )
2.5.2.4. list.sort(cmp=None, key=None, reverse=False)1 2 3 4 5 6 7 8 9 10 11 12 13 nums = [3 , 1 , 4 , 2 ] nums.sort() nums.sort(reverse=True ) def takeSecond (elem ): return elem[1 ] random = [(2 , 2 ), (3 , 4 ), (4 , 1 ), (1 , 3 )] random.sort(key=takeSecond)
2.5.2.5. list.reverse()1 2 nums = [1 , 2 , 3 ] nums.reverse()
2.5.2.6. list.remove(obj)删掉第一个匹配的1 2 3 list1 = ['Google' , 'Runoob' , 'Taobao' , 'Baidu' ] list1.remove('Taobao' ) list1.remove('Baidu' )
2.5.3. 字典 (dict) 2.5.3.1. dict.get(key, default)1 2 3 4 5 counts = {'a' : 2 , 'b' : 1 } val1 = counts.get('b' , 0 ) val2 = counts.get('c' , 0 )
2.5.3.2. dict.keys()1 2 3 4 5 counts = {'a' : 2 , 'b' : 1 } for key in counts.keys(): print (key) sorted_keys = sorted (counts.keys())
2.5.3.3. dict.values()1 2 3 4 5 counts = {'a' : 2 , 'b' : 1 } for value in counts.values(): print (value) values_list = list (counts.values())
2.5.3.4. dict.items()1 2 3 4 5 counts = {'a' : 2 , 'b' : 1 } for key, value in counts.items(): print (f"{key} : {value} " )
2.6. Collections 2.6.1. defaultdict使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict1 dd = defaultdict(lambda : 'N/A' )
使用lambda 可创建默认值 否则的话默认是0
这边还在等待更新中 其实是刷题刷着刷着觉得应该开始总结经验还有防止忘记