添加Go语言题解

This commit is contained in:
zouxinyao
2021-07-28 02:26:32 +08:00
parent 7eb8b4a9fd
commit 575b7612f0
52 changed files with 1679 additions and 104 deletions

View File

@@ -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 种解题方法肯定还有别的方法欢迎大家讨论大家可以在做题的时候一题多解这样能大大提高自己解题能力下面我们来看一下这些方法如何应用到其他题目上

View File

@@ -2,7 +2,7 @@
>
> 感谢支持该仓库会一直维护希望对各位有一丢丢帮助
>
> 另外希望手机阅读的同学可以来我的 <u>[**公众号袁厨的算法小屋**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
> 另外希望手机阅读的同学可以来我的 <u>[**公众号袁厨的算法小屋**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [137. 只出现一次的数字 II](https://leetcode-cn.com/problems/single-number-ii/)
@@ -216,6 +216,27 @@ class Solution:
return res
```
Go Code:
```go
func singleNumber(nums []int) int {
res := 0
// Go语言中int占32位以上
for i := 0; i < 64; i++ {
cnt := 0
for j := 0; j < len(nums); j++ {
if (nums[j] >> i & 1) == 1 {
cnt++
}
}
if cnt % 3 != 0{
res = res | 1 << i
}
}
return res
}
```
我们来解析一下我们的代码
> **<<** 左移运算符运算数的各二进位全部左移若干位 **<<** 右边的数字指定了移动的位数高位丢弃低位补 0

View File

@@ -263,3 +263,26 @@ class Solution:
arr[1] ^= y
return arr
```
Go Code:
```go
func singleNumber(nums []int) []int {
temp := 0
for _, x := range nums {
temp ^= x
}
// 保留最后那个1为了区分两个数
group := temp & (^temp + 1)
res := make([]int, 2)
for _, x := range nums {
if group & x == 0{
res[0] ^= x
} else {
res[1] ^= x
}
}
return res
}
```