mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-09 08:31:36 +00:00
添加Go语言题解
This commit is contained in:
@@ -131,6 +131,26 @@ class Solution:
|
||||
return y
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func singleNumber(nums []int) int {
|
||||
if len(nums) == 1 {
|
||||
return nums[0]
|
||||
}
|
||||
m := map[int]int{}
|
||||
for _, x := range nums {
|
||||
m[x]++
|
||||
}
|
||||
for k, v := range m {
|
||||
if v == 1 {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
```
|
||||
|
||||
### 排序搜索法
|
||||
|
||||
#### 解析
|
||||
@@ -208,6 +228,28 @@ class Solution:
|
||||
return nums[len(nums) - 1]
|
||||
```
|
||||
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func singleNumber(nums []int) int {
|
||||
if len(nums) == 1 {
|
||||
return nums[0]
|
||||
}
|
||||
sort.Ints(nums)
|
||||
for i := 1; i < len(nums) - 1; i+=2 {
|
||||
if nums[i] == nums[i - 1] {
|
||||
continue
|
||||
} else {
|
||||
return nums[i - 1]
|
||||
}
|
||||
}
|
||||
return nums[len(nums) - 1]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### HashSet
|
||||
|
||||
#### 解析
|
||||
@@ -565,4 +607,17 @@ class Solution:
|
||||
return reduce(lambda num, x: num ^ x, nums, 0)
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func singleNumber(nums []int) int {
|
||||
res := 0
|
||||
for _, x := range nums {
|
||||
res ^= x
|
||||
}
|
||||
return res
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
本题一共介绍了 6 种解题方法,肯定还有别的方法,欢迎大家讨论。大家可以在做题的时候一题多解。这样能大大提高自己解题能力。下面我们来看一下这些方法如何应用到其他题目上。
|
||||
|
Reference in New Issue
Block a user