From 8d552eb9d48f9ac517af221b8c3b4aaa5c574012 Mon Sep 17 00:00:00 2001 From: zouxinyao Date: Sun, 25 Jul 2021 04:20:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=AA=E5=87=BA=E7=8E=B0=E4=B8=80=E6=AC=A1?= =?UTF-8?q?=E7=9A=84=E6=95=B0=20=E6=B7=BB=E5=8A=A0Go=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../求次数问题/只出现一次的数.md | 52 +++++++++++++++++++ .../求次数问题/只出现一次的数2.md | 21 ++++++++ .../求次数问题/只出现一次的数3.md | 23 ++++++++ 3 files changed, 96 insertions(+) diff --git a/animation-simulation/求次数问题/只出现一次的数.md b/animation-simulation/求次数问题/只出现一次的数.md index ce31252..de966a8 100644 --- a/animation-simulation/求次数问题/只出现一次的数.md +++ b/animation-simulation/求次数问题/只出现一次的数.md @@ -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种解题方法,肯定还有别的方法,欢迎大家讨论。大家可以在做题的时候一题多解。这样能大大提高自己解题能力。下面我们来看一下这些方法如何应用到其他题目上。 \ No newline at end of file diff --git a/animation-simulation/求次数问题/只出现一次的数2.md b/animation-simulation/求次数问题/只出现一次的数2.md index 31b47e1..b1ce2b3 100644 --- a/animation-simulation/求次数问题/只出现一次的数2.md +++ b/animation-simulation/求次数问题/只出现一次的数2.md @@ -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。 diff --git a/animation-simulation/求次数问题/只出现一次的数3.md b/animation-simulation/求次数问题/只出现一次的数3.md index a33da9e..050e3d3 100644 --- a/animation-simulation/求次数问题/只出现一次的数3.md +++ b/animation-simulation/求次数问题/只出现一次的数3.md @@ -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 +} +``` +