修改目录名称
This commit is contained in:
30
哈希/两数之和/main.go
Normal file
30
哈希/两数之和/main.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println(twoSum([]int{3, 3}, 6))
|
||||
}
|
||||
|
||||
func twoSum(nums []int, target int) []int {
|
||||
hash := make(map[int][]int)
|
||||
for i := 0; i < len(nums); i++ {
|
||||
hash[nums[i]] = append(hash[nums[i]], i)
|
||||
}
|
||||
fmt.Println(hash)
|
||||
var result []int
|
||||
for k, v := range hash {
|
||||
if k == target/2 && len(v) > 1 {
|
||||
result = append(result, v...)
|
||||
return result
|
||||
} else if k == target/2 && len(v) == 1 {
|
||||
continue
|
||||
}
|
||||
if val, ok := hash[target-k]; ok {
|
||||
result = append(result, v[0])
|
||||
result = append(result, val[0])
|
||||
return result
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
36
哈希/字母异次分组/main.go
Normal file
36
哈希/字母异次分组/main.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(groupAnagrams([]string{"a"}))
|
||||
}
|
||||
|
||||
func groupAnagrams(strs []string) [][]string {
|
||||
hash := make(map[string][]int)
|
||||
result := make([][]string, 0)
|
||||
for value, str := range strs {
|
||||
runes := []rune(str)
|
||||
sort.Slice(runes, func(i, j int) bool {
|
||||
return runes[i] < runes[j]
|
||||
})
|
||||
if _, ok := hash[string(runes)]; ok {
|
||||
hash[string(runes)] = append(hash[string(runes)], value)
|
||||
} else {
|
||||
hash[string(runes)] = make([]int, 0)
|
||||
hash[string(runes)] = append(hash[string(runes)], value)
|
||||
}
|
||||
}
|
||||
for _, value := range hash {
|
||||
tmp := make([]string, 0)
|
||||
for _, value := range value {
|
||||
tmp = append(tmp, strs[value])
|
||||
}
|
||||
result = append(result, tmp)
|
||||
}
|
||||
return result
|
||||
|
||||
}
|
||||
42
哈希/最长连续序列/main.go
Normal file
42
哈希/最长连续序列/main.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(longestConsecutive([]int{0}))
|
||||
}
|
||||
|
||||
func longestConsecutive(nums []int) int {
|
||||
exist := make(map[int]struct{})
|
||||
hash := make(map[int]int)
|
||||
maxresult := 0
|
||||
sort.Slice(nums, func(i, j int) bool {
|
||||
return nums[i] < nums[j]
|
||||
})
|
||||
for i := 0; i < len(nums); i++ {
|
||||
exist[nums[i]] = struct{}{}
|
||||
}
|
||||
for i := 0; i < len(nums); i++ {
|
||||
j := nums[i]
|
||||
v := 0
|
||||
for {
|
||||
j++
|
||||
if _, ok := exist[j]; ok {
|
||||
v += 1
|
||||
if _, okk := exist[j+1]; okk {
|
||||
delete(exist, j)
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
hash[nums[i]] = v + 1
|
||||
if v >= maxresult {
|
||||
maxresult = v + 1
|
||||
}
|
||||
}
|
||||
return maxresult
|
||||
}
|
||||
Reference in New Issue
Block a user