只出现一次的数 添加Go语言代码

pull/43/head
zouxinyao 2021-07-25 04:20:42 +08:00
parent d9e076483c
commit 8d552eb9d4
3 changed files with 96 additions and 0 deletions

View File

@ -55,6 +55,26 @@ class Solution {
}
```
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
}
```
###
####
@ -86,6 +106,25 @@ class Solution {
}
```
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
@ -234,4 +273,17 @@ class Solution {
}
```
Go Code:
```go
func singleNumber(nums []int) int {
res := 0
for _, x := range nums {
res ^= x
}
return res
}
```
6

View File

@ -92,6 +92,27 @@ class Solution {
}
```
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

@ -111,3 +111,26 @@ class Solution {
}
```
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
}
```