当前位置:网站首页>[go language questions] go from 0 to entry 4: advanced usage of slice, elementary review and introduction to map
[go language questions] go from 0 to entry 4: advanced usage of slice, elementary review and introduction to map
2022-06-24 11:33:00 【Study notes of Zhou】
Go from 0 To the beginning 4
Preface
- This period is for learning Golang Of : Advanced usage and elementary review of slicing 、Map、 Introduction to conditional and circular statements , If you don't understand something, you can comment and discuss it !
- This series of articles adopts the core code mode of Niuke to provide case code , Help you from 0 To the beginning of the learning process of supporting brush questions ~
- I recommend a brush question for you 、 Interview artifact , I also use this artifact to learn !~ Links are as follows : Brush question artifact jump link
- The artifact not only has a beautiful web interface , And the operation is very easy to get started ! It is very suitable for beginners to learn systematically !
- Novice Xiaobai can use this artifact to brush questions everyday 、 Look at the face of Dachang 、 Learn the basics of computer 、 Communicate with Daniel face to face ~ The picture of question brushing has been placed below ~

Q1: section - Out of the team
Problem description : The students all lined up , There is a slice showing the height of the corresponding students , Now people who randomly call a certain position are out of the team , Return to the slice after leaving the team . such as [2,3,4,5], The index for 1 Out of line at , After leaving the team, the slices were [2,4,5]
Related knowledge :
1、s|n| section s The index position is n The item
2、s|:| From slice s Index position of 0 To len(s)-1 Slices obtained at
3、s|low:| From slice s Index position of low To len(s)-1 Slices obtained at
4、s|:high| From slice s Index position of 0 To high Slices obtained at ,len=high
5、s|low: high| From slice s The prime reference position of Iow To high Slices obtained at ,len-high-low
6、s|low: high:max| From slice s The prime reference position of low To high Slices obtained at ,len-high-low, cap=max-low
Sample input :[1,2,3,4,5,6],3
Sample output :[1,2,3,5,6]
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param s int Integer one-dimensional array height * @param index int integer Out of line index * @return int Integer one-dimensional array */
func deleteElement(s []int, index int) []int {
// write code here
s1 := s[0 : index]
s2 := s[index+1:]
s1 = append(s1, s2...)
return s1
}
Q2: Slice traversal - Judges rate
Problem description : Xiao Ming takes part in a singing competition , The judges will rate , Ask to remove the highest score , And the lowest score , Save the highest score and the lowest score into the slice and return .
Related knowledge :
1、int64 Maximum , minimum value , Size comparison , Multiple return values
2、golang The maximum signed value in is math.MaxInt64, The minimum value is math.MinInt64
3、 There are two ways to traverse slices ,for Circulation and for range loop
Sample input :[1,2,3,4,5,6,7,8,9]
Sample output :[1,9]
Case code :
func minAndMax(s []int) []int {
// write code here
var ans []int
var a int = s[0]
var b int = s[0]
for _, j := range s {
a = max(a, j)
b = min(b, j)
}
ans = append(ans, b)
ans = append(ans, a)
return ans
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
Q3: Slice traversal - Adjust the order
Problem description : The children stood in a row in turn , Now we need to change their order , Reverse row , Stand on the far left from the rightmost person , The person on the penultimate right stands in the second position on the leftmost side , And so on . For example, the order of children is [1,3,2,3,4,6], Rearranged as [6,4,3,2,3,1].
Related knowledge :
1、len(slice) Find the length of a slice
2、for Loop through slices
3、 The multiple assignment feature makes it easy to exchange variables , Variable one , Variable two := Variable two , Variable one
Sample input :[1,2,3,4,5,6,7,8,9]
Sample output :[9,8,7,6,5,4,3,2,1]
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param s int Integer one-dimensional array * @return int Integer one-dimensional array */
func convert(s []int) []int {
// write code here
length := len(s)
for i := 0; i < length/2; i++{
s[i], s[length-i-1] = s[length-i-1], s[i]
// tmp := s[i]
// s[i] = s[length-i-1]
// s[length-i-1] = tmp
}
return s
}
Q4: Slice traversal - Determine whether two slices have the same elements
Problem description : Given two slices , Determine whether the elements in the two slices are exactly the same .
Related knowledge :
1、len(slice) Find the length of a slice
2、for Loop through slices
Sample input :[1,2,3,4],[1,2,3,4]
Sample output :true
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param s1 int Integer one-dimensional array * @param s2 int Integer one-dimensional array * @return bool Boolean type */
func equal( s1 []int , s2 []int ) bool {
// write code here
length := len(s1)
for i := 0; i < length; i++{
if s1[i] != s2[i]{
return false
}
}
return true
}
Q5: Merge ordered arrays
Problem description : Here are two buttons Non decreasing order Array of arranged integers nums1 and nums2, There are two other integers m and n , respectively nums1 and nums2 The number of elements in . Would you please Merge nums2 To nums1 in , Make the merged array press Non decreasing order array . Be careful : Final , The merged array should not be returned by the function , It's stored in an array nums1 in . In response to this situation ,nums1 The initial length of is m + n, The top m Elements represent the elements that should be merged , after n Elements are 0 , It should be ignored .nums2 The length of is n .
Related knowledge :
1、for loop
2、break Break the loop
3、append Addition of slices
Sample input :[1,2,3,0,0,0],3,[2,5,6],3
Sample output :[1,2,2,3,5,6]
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param nums1 int Integer one-dimensional array * @param m int integer * @param nums2 int Integer one-dimensional array * @param n int integer * @return int Integer one-dimensional array */
func merge(nums1 []int, m int, nums2 []int, n int) []int {
// write code here
// similar Merge sort From the back Start judging Put the big one return
i := m + n - 1
p1 := m - 1
p2 := n - 1
for p1 >= 0 && p2 >= 0 {
if nums1[p1] >= nums2[p2] {
nums1[i] = nums1[p1]
p1--
i--
} else {
nums1[i] = nums2[p2]
p2--
i--
}
}
for p1 >= 0 {
nums1[i] = nums1[p1]
p1--
i--
}
for p2 >= 0 {
nums1[i] = nums2[p2]
p2--
i--
}
return nums1
}
Q6:Map- League tables
Problem description : A university dormitory 6 People's math scores are Xiao Ming :60, Xiao Wang :70, Zhang San :95, Li Si :98, Wang Wu :100, Zhang Wei :88 , Now I want to enter the scores of the six students into the score sheet , This grade sheet uses a map To express , The key of the grade sheet is the name of the dormitory member , The value is the corresponding fraction . Print the grade sheet
Related knowledge :
1、map Statement of :map[KeyType]ValueType KeyType: Represents the type of key .ValueType: Represents the type of value corresponding to the key .map The default initial value of a variable of type is nil, Need to use make() Function to allocate memory . The grammar is :make(map[KeyType]ValueType, [cap]) among cap Express map The capacity of , This parameter is not required , But we should be initializing map When the time for its designated a suitable capacity .
2、map[key]=value To assign to key Assign a designated value
Sample input :
Sample output :map[ Xiao Ming :60 Xiao Wang :70 Zhang San :95 Zhang Wei :88 Li Si :98 Wang Wu :100]
Case code :
import "fmt"
func main() {
m1 := make(map[string]int)
m1[" Xiao Ming "] = 60
m1[" Xiao Wang "] = 70
m1[" Zhang San "] = 95
m1[" Zhang Wei "] = 88
m1[" Li Si "] = 98
m1[" Wang Wu "] = 100
fmt.Println(m1)
}
Q7:Map- Word characters
Problem description : Given a string consisting only of letters and numbers ,, Count the number of occurrences of each character , And returns the most frequently occurring character .
Related knowledge :
1、 The elements that make up each string are called “ character ”, You can get the character by traversing or getting a single string element . The characters are in single quotation marks (’) Wrap it up , Such as :var a = ‘ in ’
2、map Each key Is the only one. .
3、map Statement of :map[KeyType]ValueType KeyType: Represents the type of key .ValueType: Represents the type of value corresponding to the key .map The default initial value of a variable of type is nil, Need to use make() Function to allocate memory . The grammar is :make(map[KeyType]ValueType, [cap]) among cap Express map The capacity of , This parameter is not required , But we should be initializing map When the time for its designated a suitable capacity .
Sample input :“yyds”
Sample output :y
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param s string character string * @return char Character */
func character(s string) byte {
// write code here
arr := ([]byte)(s)
count := 0
var ans byte
charaMap := make(map[byte]int)
for _, j := range arr {
charaMap[j]++
if charaMap[j] > count {
count = charaMap[j]
ans = j
}
}
return ans
}
later : Brush Title artifact
Click the link to jump to registration , Start your nanny level question brushing ! Brush the questions and write strange codes. The way of God
In addition, we can not only brush questions here , There will be everything you want , It is very suitable for Xiaobai and beginners ~
1、 Algorithm (398 topic ): Interview must brush 100 topic 、 Introduction to algorithm 、 Interview frequency list
2、 Data structure (300 topic ): Are very classic linked lists 、 Trees 、 Pile up 、 Stack 、 queue 、 Dynamic planning, etc
3、 Language (500 topic ):C/C++、java、python Introductory algorithm exercises
4、SQL piece (82 topic ): Quick start 、SQL Will know 、SQL Advanced challenges 、 The real question of the interview
5、 The real question of the written test of Dachang : Bytes to beat 、 Meituan 、 Baidu 、 tencent … Master the experience and don't be afraid of the interview !

边栏推荐
- 图片的可视化呈现有效增强大屏吸引力
- Turn 2D photos into 3D models to see NVIDIA's new AI "magic"!
- u盘安装kali并且持久化
- I just did it! Visualization of character relationships in Douluo continent
- Introduction to C language circular statements (foe, while, do... While)
- Nacos source code - configure automatic update
- 脚本之美│VBS 入门交互实战
- 10 zeros of D
- 夜晚读书 -- 关于微服务和容器
- How to develop hospital information system (his) with SMS notification and voice function
猜你喜欢

历史上的今天:图灵诞生日;互联网奠基人出生;Reddit 上线

Use the process monitor tool to monitor process operations on registries and files

电商红包雨是如何实现的?拿去面试用(典型高并发)
![[digital ic/fpga] booth multiplier](/img/42/3da3b1d3cc82cb9c0694241148011b.png)
[digital ic/fpga] booth multiplier

New progress in the construction of meituan's Flink based real-time data warehouse platform

《opencv学习笔记》-- 离散傅里叶变换

ArrayList#subList这四个坑,一不小心就中招

Today's sleep quality record 76 points

如何优雅的写 Controller 层代码?

Programmers spend most of their time not writing code, but...
随机推荐
Nxshell session management supports import and export
H5 video conference, camera monitoring, web streaming and live broadcast integration scheme
How to use data analysis tools to deal with emergencies in retail industry
[206] use PHP language to generate the code of go language
【云驻共创】解读HarmonyOS 应用与服务生态
How to export only the titles in word documents? (i.e. delete all the text contents and keep only the title) stop B
Cook a delicious cli
It's so difficult for me. Have you met these interview questions?
First acquaintance with string+ simple usage (I)
[live review] battle code pioneer phase 7: how third-party application developers contribute to open source
Fizz gateway secondary development integration tutorial
Any and typevar make the automatic completion of IDE better
[the lottery in May has ended, and the list of winners has been announced] special session of techo youth university open course database
程序员大部分时间不是写代码,而是。。。
System design: key features of distributed systems
Realization of alarm clock with AHK
How to open a video number?
Use the process monitor tool to monitor process operations on registries and files
2008R2 precautions for configuring L2TP pre shared key VPN
Istio best practice: graceful termination