pseudoyu

pseudoyu

Blockchain | Programming | Photography | Boyi
github
twitter
telegram
mastodon
bilibili
jike

Common Data Structures for LeetCode Problem Solving (Go Edition)

Introduction#

Recently, I started using Go to solve LeetCode algorithm problems. When it comes to solving algorithm problems for work, the focus is mainly on developing problem-solving skills and coding abilities, rather than using complex data structures like in algorithm competitions. Therefore, there are not many commonly used data structures and operations. However, mastering them can greatly improve the quality of your code. In this article, I will provide a summary for easy reference.

Data Structures#

Arrays#

Initialization#

// Initialize an array of size 10 with default value 0
nums := make([10]int)

// Initialize a 2D boolean array
visited := make([5][10]int)

Common Methods#

for i := 0; i < len(nums); i++ {
    // Access nums[i]
}

Strings#

Initialization#

s1 := "hello world"

// Create a multiline string
s2 := `This is a
multiline
string.`

Accessing Strings#

// You can directly access bytes (not characters) using indexes
s1 := "hello world"
first := s[0]

s2 := []byte(s1)
first := s2[0]

Modifying Strings#

// Strings are immutable, but you can assign a new string value
s := "hello"
t := s

// Convert the string to []byte or []rune to modify it
s1 := "hello world"
s2 := []byte(s1)
s2[0] = 'H'
s3 := string(s2)

Checking if a Character Belongs to a Specific Character Set#

// Check if the character at index i of string s is a vowel
if strings.Contains("aeiouAEIOU", string(s[i])) {
    // ...
}

Comparing Strings#

if s1 == s2 {
    // Equal
} else {
    // Not equal
}

// The Compare function can be used for comparison, where 1 means greater, 0 means equal, and -1 means smaller
// The EqualFold function compares strings ignoring case

Concatenating Strings#

// You can use + to concatenate strings, but it is not efficient
s1 := "hello "
s2 := s1 + "world"

Efficient String Concatenation#

// Use bytes.Buffer to concatenate strings at once
var b bytes.Buffer
b.WriteString("Hello ")
b.WriteString("World")
b1 := b.String()

// Concatenate multiple strings
var strs []string
strings.Join(strs, "World")

Converting Integers (or any data type) to Strings#

// Use Itoa conversion
i := 123
t := strconv.Itoa(i)

// Use Sprintf conversion
i := 123
t := fmt.Sprintf("%d", i)

Slices#

Initialization#

// Initialize a slice to store strings
slice := make([]string, 0)
slice := []string

// Initialize a slice to store integers
slice := make([]int, 0)
slice := []int

Common Methods#

// Check if the slice is empty
if len(slice) == 0 {
    // Empty
}

// Get the number of elements
len()

// Access an element at an index
slice[i]

// Append an element at the end
slice = append(slice, 1)

Simulating Stacks and Queues Using Slices#

Stack#

// Create a stack
stack := make([]int, 0)
// Push an element
stack = append(stack, 10)
// Pop an element
v := stack[len(stack) - 1]
stack = stack[:len(stack) - 1]
// Check if the stack is empty
len(stack) == 0

Queue#

// Create a queue
queue := make([]int, 0)
// Enqueue an element
queue = append(queue, 10)
// Dequeue an element
v := queue[0]
queue = queue[1:]
// Check if the queue is empty
len(queue) == 0

Maps#

// Create a map
m := make(map[string]int)
// Set key-value pairs
m["hello"] = 1
// Delete a key
delete(m,"hello")
// Iterate over the map
for k, v := range m{
    // Perform operations
}

// Map keys must be comparable and cannot be slices, maps, or functions
// Map values have default values and can be directly manipulated, e.g., m[age]++ changes the value from 0 to 1
// Comparing two maps requires iterating over them and checking if the key-value pairs are the same, considering the default values

Standard Library#

sort#

// Sort integers
sort.Ints([]int{})
// Sort strings
sort.Strings([]string{})

math#

// int32 maximum and minimum values
math.MaxInt32
math.MinInt32
// int64 maximum and minimum values (int defaults to int64)
math.MaxInt64
math.MinInt64

copy#

// To delete a[i], you can use copy to overwrite the values from i+1 to the end to i, and then decrease the length by 1
copy(a[i:], a[i+1:])
a = a[:len(a)-1]

// If you create a slice with a specific length using make, you can assign values by index
a := make([]int, n)
a[n] = x

// If you create a slice with a length of 0 using make, you can assign values using append()
a := make([]int, 0)
a = append(a, x)

Type Conversion#

// Convert byte to number
s = "12345"  // s[0] is of type byte
num := int(s[0] - '0') // 1
str := string(s[0]) // "1"
b := byte(num + '0') // '1'
fmt.Printf("%d%s%c\n", num, str, b) // 111

// Convert string to number
num, _ := strconv.Atoi()
str := strconv.Itoa()

Conclusion#

The journey of coding practice is long... Keep going!

References#

  1. LeetCode Official Website
  2. greyireland/algorithm-pattern
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.