Go练习题(2)

/*
1.整理当天的知识点
2.找int切片中最大的元素
3.找int切片中第二的最大的元素
4.获取映射中所有key组成的切片
5.获取映射中所有value组成的切片
6.一段英文 每个字符出现的次数 rune => int
 count => []rune
 a = 2
 b = 3
 c = 2
7.冒泡排序
8.挑战:插入排序(百度百科 直接插入排序)
9.挑战: 猜数字(折半猜),查找算法 => 针对有序切片=> 找元素=> 二分查找
	sort.Search*** => 插入的位置 元素存在/元素不存在
*/
package main

import (
	"fmt"
	"sort"
)

func main() {
	//2
	num := []int{5, 1, 5, 6, 7, 8}
	//第一种方法直接用sort
	sort.Ints(num)
	fmt.Println(num[len(num)-1])
	num = []int{5, 1, 5, 6, 7, 8}
	//第二种方法
	for i := 0; i < len(num)-1; i++ {
		if num[i] > num[i+1] {
			num[i], num[i+1] = num[i+1], num[i]
		}
	}
	fmt.Println(num[len(num)-1])

	//3
	//第一种方法直接用sort
	sort.Ints(num)
	fmt.Println(num[len(num)-2])
	num = []int{5, 1, 5, 6, 7, 8}
	//第二种方法
	for j := 0; j < 2; j++ {
		for i := 0; i < len(num)-1; i++ {
			if num[i] > num[i+1] {
				num[i], num[i+1] = num[i+1], num[i]
			}
		}
	}
	fmt.Println(num[len(num)-2])

	//4,5
	num01 := map[string]int{"aaa": 123, "bbb": 56}
	var num02 []string
	var num03 []int
	for k, v := range num01 {
		num02 = append(num02, k)
		num03 = append(num03, v)
	}
	fmt.Println(num02, num03)

	//6
	bbb := `Wednesday, March 04, 2020
	Contributor Summit Amsterdam Postponed
	Authors: Dawn Foster (VMware), Jorge Castro (VMware)
	The CNCF has announced that KubeCon + CloudNativeCon EU has been delayed until July/August of 2020. As a result the Contributor Summit planning team is weighing options for how to proceed. Here’s the current plan:
	
	There will be an in-person Contributor Summit as planned when KubeCon + CloudNativeCon is rescheduled.
	We are looking at options for having additional virtual contributor activities in the meantime.
	We will communicate via this blog and the usual communications channels on the final plan. Please bear with us as we adapt when we get more information. Thank you for being patient as the team pivots to bring you a great Contributor Summit!`
	ccc := map[rune]int{}
	for _, v := range bbb {
		if v > 'a' && v < 'z' || v > 'A' && v < 'Z' {
			ccc[v]++
		}
	}
	for k, v := range ccc {
		fmt.Printf("%q %d\n", k, v)
	}
	//我们想要的答案是
	/*
		10 = [a,b]
		出现10次的有什么
	*/
	countStats := map[int][]rune{}
	for k, v := range ccc {
		// countStats[v] = append(countStats[v], k)
		if _, ok := countStats[v]; ok {
			countStats[v] = append(countStats[v], k)
		} else {
			countStats[v] = []rune{k}
		}
	}
	// for k, v := range countStats {
	// 	fmt.Printf("%#v %q\n", k, v)
	// }
	ddd := []int{}
	for k := range countStats {
		ddd = append(ddd, k)
	}
	fmt.Println(ddd)
	sort.Ints(ddd)
	fmt.Println(ddd)
	for _, v := range ddd {
		fmt.Printf("出现%d次的有 %q\n", v, countStats[v])
	}
}
发布了92 篇原创文章 · 获赞 12 · 访问量 5696

猜你喜欢

转载自blog.csdn.net/weixin_45413603/article/details/104784776