# 【golang】leetcode初级-旋转数组&存在重复元素

wric

## 第一题 旋转数组

### 题目信息

1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105

### 解题思路

// reverse reverses a slice of ints in place.
func reverse(s []int) {

``````for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}``````

}

a := [...]int{0, 1, 2, 3, 4, 5}
reverse(a[:])
fmt.Println(a) // "[5 4 3 2 1 0]"

s := []int{0, 1, 2, 3, 4, 5}
// Rotate s left by two positions.
reverse(s[:2])
reverse(s[2:])
reverse(s)
fmt.Println(s) // "[2 3 4 5 0 1]"

### 详细代码

``````func rotate(nums []int, k int)  {
n:=len(nums)
if k>=n {
k=k%n
}
if n==1{
fmt.Println(nums)
}else{
reverse(nums[n-k:n])
reverse(nums[:n-k])
reverse(nums)
fmt.Println(nums)
}
}
func reverse(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}``````

### 代码优化

``````func reverse(a []int) {
for i, n := 0, len(a); i < n/2; i++ {
a[i], a[n-1-i] = a[n-1-i], a[i]
}
}

func rotate(nums []int, k int) {
k %= len(nums)
reverse(nums)
reverse(nums[:k])
reverse(nums[k:])
}

### 另一种解法

``````有AB = xaxb，由于x是最大公因数，所以a、b互质。

## 第二题 存在重复元素

### 代码

``````func containsDuplicate(nums []int) bool {
m := map[int] int{}
for _,num:= range nums{
m[num]++
}
for _, frequency := range m {
if frequency > 1{
return true
}
}
return false
}``````

10 声望
3 粉丝
0 条评论