添加 16 题

This commit is contained in:
YDZ
2020-08-11 17:20:53 +08:00
parent 388e1fb902
commit 9f47c758c9
64 changed files with 4149 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package leetcode
func findDisappearedNumbers(nums []int) []int {
res := []int{}
for _, v := range nums {
if v < 0 {
v = -v
}
if nums[v-1] > 0 {
nums[v-1] = -nums[v-1]
}
}
for i, v := range nums {
if v > 0 {
res = append(res, i+1)
}
}
return res
}

View File

@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question448 struct {
para448
ans448
}
// para 是参数
// one 代表第一个参数
type para448 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans448 struct {
one []int
}
func Test_Problem448(t *testing.T) {
qs := []question448{
question448{
para448{[]int{4, 3, 2, 7, 8, 2, 3, 1}},
ans448{[]int{5, 6}},
},
question448{
para448{[]int{4, 3, 2, 10, 9, 2, 3, 1, 1, 1, 1}},
ans448{[]int{5, 6, 7, 8, 11}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 448------------------------\n")
for _, q := range qs {
_, p := q.ans448, q.para448
fmt.Printf("【input】:%v 【output】:%v\n", p, findDisappearedNumbers(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,53 @@
# [448. Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)
## 题目
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
**Example**:
```
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
```
## 题目大意
给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。找到所有在 [1, n] 范围之间没有出现在数组中的数字。你能在不使用额外空间且时间复杂度为 O(n) 的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
## 解题思路
- 找出 [1,n] 范围内没有出现在数组中的数字。要求不使用额外空间,并且时间复杂度为 O(n)。
- 要求不能使用额外的空间,那么只能想办法在原有数组上进行修改,并且这个修改是可还原的。时间复杂度也只能允许我们一层循环。只要循环一次能标记出已经出现过的数字,这道题就可以按要求解答出来。这里笔者的标记方法是把 |nums[i]|-1 索引位置的元素标记为负数。即 nums[| nums[i] |- 1] * -1。这里需要注意的是nums[i] 需要加绝对值,因为它可能被之前的数置为负数了,需要还原一下。最后再遍历一次数组,若当前数组元素 nums[i] 为负数,说明我们在数组中存在数字 i+1。把结果输出到最终数组里即可。
## 代码
```go
func findDisappearedNumbers(nums []int) []int {
res := []int{}
for _, v := range nums {
if v < 0 {
v = -v
}
if nums[v-1] > 0 {
nums[v-1] = -nums[v-1]
}
}
for i, v := range nums {
if v > 0 {
res = append(res, i+1)
}
}
return res
}
```

View File

@ -0,0 +1,16 @@
package leetcode
func findMaxConsecutiveOnes(nums []int) int {
maxCount, currentCount := 0, 0
for _, v := range nums {
if v == 1 {
currentCount++
} else {
currentCount = 0
}
if currentCount > maxCount {
maxCount = currentCount
}
}
return maxCount
}

View File

@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question485 struct {
para485
ans485
}
// para 是参数
// one 代表第一个参数
type para485 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans485 struct {
one int
}
func Test_Problem485(t *testing.T) {
qs := []question485{
question485{
para485{[]int{1, 1, 0, 1, 1, 1}},
ans485{3},
},
question485{
para485{[]int{1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1}},
ans485{4},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 485------------------------\n")
for _, q := range qs {
_, p := q.ans485, q.para485
fmt.Printf("【input】:%v 【output】:%v\n", p, findMaxConsecutiveOnes(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,55 @@
# [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)
## 题目
Given a binary array, find the maximum number of consecutive 1s in this array.
**Example 1**:
```
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
```
**Note**:
- The input array will only contain `0` and `1`.
- The length of input array is a positive integer and will not exceed 10,000
## 题目大意
给定一个二进制数组, 计算其中最大连续1的个数。
注意:
- 输入的数组只包含 0 和 1。
- 输入数组的长度是正整数,且不超过 10,000。
## 解题思路
- 给定一个二进制数组, 计算其中最大连续1的个数。
- 简单题。扫一遍数组,累计 1 的个数,动态维护最大的计数,最终输出即可。
## 代码
```go
func findMaxConsecutiveOnes(nums []int) int {
maxCount, currentCount := 0, 0
for _, v := range nums {
if v == 1 {
currentCount++
} else {
currentCount = 0
}
if currentCount > maxCount {
maxCount = currentCount
}
}
return maxCount
}
```

View File

@ -0,0 +1,60 @@
package leetcode
func imageSmoother(M [][]int) [][]int {
res := make([][]int, len(M))
for i := range M {
res[i] = make([]int, len(M[0]))
}
for y := 0; y < len(M); y++ {
for x := 0; x < len(M[0]); x++ {
res[y][x] = smooth(x, y, M)
}
}
return res
}
func smooth(x, y int, M [][]int) int {
count, sum := 1, M[y][x]
// Check bottom
if y+1 < len(M) {
sum += M[y+1][x]
count++
}
// Check Top
if y-1 >= 0 {
sum += M[y-1][x]
count++
}
// Check left
if x-1 >= 0 {
sum += M[y][x-1]
count++
}
// Check Right
if x+1 < len(M[y]) {
sum += M[y][x+1]
count++
}
// Check Coners
// Top Left
if y-1 >= 0 && x-1 >= 0 {
sum += M[y-1][x-1]
count++
}
// Top Right
if y-1 >= 0 && x+1 < len(M[0]) {
sum += M[y-1][x+1]
count++
}
// Bottom Left
if y+1 < len(M) && x-1 >= 0 {
sum += M[y+1][x-1]
count++
}
//Bottom Right
if y+1 < len(M) && x+1 < len(M[0]) {
sum += M[y+1][x+1]
count++
}
return sum / count
}

View File

@ -0,0 +1,52 @@
package leetcode
import (
"fmt"
"testing"
)
type question661 struct {
para661
ans661
}
// para 是参数
// one 代表第一个参数
type para661 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans661 struct {
one [][]int
}
func Test_Problem661(t *testing.T) {
qs := []question661{
question661{
para661{[][]int{[]int{1, 1, 1}, []int{1, 1, 2}}},
ans661{[][]int{[]int{1, 1, 1}, []int{1, 1, 1}}},
},
question661{
para661{[][]int{[]int{1, 1, 1}, []int{1, 1, 2}, []int{1, 1, 1}}},
ans661{[][]int{[]int{1, 1, 1}, []int{1, 1, 1}, []int{1, 1, 1}}},
},
question661{
para661{[][]int{[]int{1, 1, 1}, []int{1, 0, 1}, []int{1, 1, 1}}},
ans661{[][]int{[]int{0, 0, 0}, []int{0, 0, 0}, []int{0, 0, 0}}},
},
}
fmt.Printf("------------------------Leetcode Problem 661------------------------\n")
for _, q := range qs {
_, p := q.ans661, q.para661
fmt.Printf("【input】:%v 【output】:%v\n", p, imageSmoother(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,107 @@
# [661. Image Smoother](https://leetcode.com/problems/image-smoother/)
## 题目
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
**Example 1**:
```
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
```
**Note**:
1. The value in the given matrix is in the range of [0, 255].
2. The length and width of the given matrix are in the range of [1, 150].
## 题目大意
包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) 平均灰度的计算是周围的8个单元和它本身的值求平均如果周围的单元格不足八个则尽可能多的利用它们。
注意:
- 给定矩阵中的整数范围为 [0, 255]。
- 矩阵的长和宽的范围均为 [1, 150]。
## 解题思路
- 将二维数组中的每个元素变为周围 9 个元素的平均值。
- 简单题,按照题意计算平均值即可。需要注意的是边界问题,四个角和边上的元素,这些点计算平均值的时候,计算平均值都不足 9 个元素。
## 代码
```go
func imageSmoother(M [][]int) [][]int {
res := make([][]int, len(M))
for i := range M {
res[i] = make([]int, len(M[0]))
}
for y := 0; y < len(M); y++ {
for x := 0; x < len(M[0]); x++ {
res[y][x] = smooth(x, y, M)
}
}
return res
}
func smooth(x, y int, M [][]int) int {
count, sum := 1, M[y][x]
// Check bottom
if y+1 < len(M) {
sum += M[y+1][x]
count++
}
// Check Top
if y-1 >= 0 {
sum += M[y-1][x]
count++
}
// Check left
if x-1 >= 0 {
sum += M[y][x-1]
count++
}
// Check Right
if x+1 < len(M[y]) {
sum += M[y][x+1]
count++
}
// Check Coners
// Top Left
if y-1 >= 0 && x-1 >= 0 {
sum += M[y-1][x-1]
count++
}
// Top Right
if y-1 >= 0 && x+1 < len(M[0]) {
sum += M[y-1][x+1]
count++
}
// Bottom Left
if y+1 < len(M) && x-1 >= 0 {
sum += M[y+1][x-1]
count++
}
//Bottom Right
if y+1 < len(M) && x+1 < len(M[0]) {
sum += M[y+1][x+1]
count++
}
return sum / count
}
```

View File

@ -0,0 +1,24 @@
package leetcode
func findShortestSubArray(nums []int) int {
frequency, maxFreq, smallest := map[int][]int{}, 0, len(nums)
for i, num := range nums {
if _, found := frequency[num]; !found {
frequency[num] = []int{1, i, i}
} else {
frequency[num][0]++
frequency[num][2] = i
}
if maxFreq < frequency[num][0] {
maxFreq = frequency[num][0]
}
}
for _, indices := range frequency {
if indices[0] == maxFreq {
if smallest > indices[2]-indices[1]+1 {
smallest = indices[2] - indices[1] + 1
}
}
}
return smallest
}

View File

@ -0,0 +1,62 @@
package leetcode
import (
"fmt"
"testing"
)
type question697 struct {
para697
ans697
}
// para 是参数
// one 代表第一个参数
type para697 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans697 struct {
one int
}
func Test_Problem697(t *testing.T) {
qs := []question697{
question697{
para697{[]int{1, 2, 2, 3, 1}},
ans697{2},
},
question697{
para697{[]int{1, 2, 2, 3, 1, 4, 2}},
ans697{6},
},
question697{
para697{[]int{}},
ans697{0},
},
question697{
para697{[]int{1, 1, 1, 1, 1}},
ans697{5},
},
question697{
para697{[]int{1, 2, 2, 3, 1, 4, 2, 1, 2, 2, 3, 1, 4, 2}},
ans697{13},
},
}
fmt.Printf("------------------------Leetcode Problem 697------------------------\n")
for _, q := range qs {
_, p := q.ans697, q.para697
fmt.Printf("【input】:%v 【output】:%v\n", p, findShortestSubArray(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,76 @@
# [697. Degree of an Array](https://leetcode.com/problems/degree-of-an-array/)
## 题目
Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`.
**Example 1**:
```
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
```
**Example 2**:
```
Input: [1,2,2,3,1,4,2]
Output: 6
```
**Note**:
- `nums.length` will be between 1 and 50,000.
- `nums[i]` will be an integer between 0 and 49,999.
## 题目大意
给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。你的任务是找到与 nums 拥有相同大小的度的最短连续子数组返回其长度。
注意:
- nums.length 在 1 到 50,000 区间范围内。
- nums[i] 是一个在 0 到 49,999 范围内的整数。
## 解题思路
- 找一个与给定数组相同度的最短连续子数组,输出其长度。数组的度的定义是任一元素出现频数的最大值。
- 简单题。先统计各个元素的频次,并且动态维护最大频次和子数组的起始和终点位置。这里最短连续子数组有点“迷惑人”。这个最短子数组其实处理起来很简单。只需从前往后扫一遍,记录各个元素第一次出现的位置和最后一次出现的位置即是最短的连续子数组。然后在频次字典里面寻找和最大频次相同的所有解,有可能有多个子数组能满足题意,取出最短的输出即可。
## 代码
```go
func findShortestSubArray(nums []int) int {
frequency, maxFreq, smallest := map[int][]int{}, 0, len(nums)
for i, num := range nums {
if _, found := frequency[num]; !found {
frequency[num] = []int{1, i, i}
} else {
frequency[num][0]++
frequency[num][2] = i
}
if maxFreq < frequency[num][0] {
maxFreq = frequency[num][0]
}
}
for _, indices := range frequency {
if indices[0] == maxFreq {
if smallest > indices[2]-indices[1]+1 {
smallest = indices[2] - indices[1] + 1
}
}
}
return smallest
}
```

View File

@ -0,0 +1,34 @@
package leetcode
func fairCandySwap(A []int, B []int) []int {
hDiff, aMap := diff(A, B)/2, make(map[int]int, len(A))
for _, a := range A {
aMap[a] = a
}
for _, b := range B {
if a, ok := aMap[hDiff+b]; ok {
return []int{a, b}
}
}
return nil
}
func diff(A []int, B []int) int {
diff, maxLen := 0, max(len(A), len(B))
for i := 0; i < maxLen; i++ {
if i < len(A) {
diff += A[i]
}
if i < len(B) {
diff -= B[i]
}
}
return diff
}
func max(a, b int) int {
if a > b {
return a
}
return b
}

View File

@ -0,0 +1,65 @@
package leetcode
import (
"fmt"
"testing"
)
type question888 struct {
para888
ans888
}
// para 是参数
// one 代表第一个参数
type para888 struct {
one []int
two []int
}
// ans 是答案
// one 代表第一个答案
type ans888 struct {
one []int
}
func Test_Problem888(t *testing.T) {
qs := []question888{
question888{
para888{[]int{}, []int{}},
ans888{[]int{}},
},
question888{
para888{[]int{1, 1}, []int{2, 2}},
ans888{[]int{1, 2}},
},
question888{
para888{[]int{1, 2}, []int{2, 3}},
ans888{[]int{1, 2}},
},
question888{
para888{[]int{2}, []int{1, 3}},
ans888{[]int{2, 3}},
},
question888{
para888{[]int{1, 2, 5}, []int{2, 4}},
ans888{[]int{5, 4}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 888------------------------\n")
for _, q := range qs {
_, p := q.ans888, q.para888
fmt.Printf("【input】:%v 【output】:%v\n", p, fairCandySwap(p.one, p.two))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,106 @@
# [888. Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap/)
## 题目
Alice and Bob have candy bars of different sizes: `A[i]` is the size of the `i`-th bar of candy that Alice has, and `B[j]` is the size of the `j`-th bar of candy that Bob has.
Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (*The total amount of candy a person has is the sum of the sizes of candy bars they have*.)
Return an integer array `ans` where `ans[0]` is the size of the candy bar that Alice must exchange, and `ans[1]` is the size of the candy bar that Bob must exchange.
If there are multiple answers, you may return any one of them. It is guaranteed an answer exists.
**Example 1**:
```
Input: A = [1,1], B = [2,2]
Output: [1,2]
```
**Example 2**:
```
Input: A = [1,2], B = [2,3]
Output: [1,2]
```
**Example 3**:
```
Input: A = [2], B = [1,3]
Output: [2,3]
```
**Example 4**:
```
Input: A = [1,2,5], B = [2,4]
Output: [5,4]
```
**Note**:
- `1 <= A.length <= 10000`
- `1 <= B.length <= 10000`
- `1 <= A[i] <= 100000`
- `1 <= B[i] <= 100000`
- It is guaranteed that Alice and Bob have different total amounts of candy.
- It is guaranteed there exists an answer.
## 题目大意
爱丽丝和鲍勃有不同大小的糖果棒A[i] 是爱丽丝拥有的第 i 块糖的大小B[j] 是鲍勃拥有的第 j 块糖的大小。因为他们是朋友所以他们想交换一个糖果棒这样交换后他们都有相同的糖果总量。一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。返回一个整数数组 ans其中 ans[0] 是爱丽丝必须交换的糖果棒的大小ans[1] 是 Bob 必须交换的糖果棒的大小。如果有多个答案,你可以返回其中任何一个。保证答案存在。
提示:
- 1 <= A.length <= 10000
- 1 <= B.length <= 10000
- 1 <= A[i] <= 100000
- 1 <= B[i] <= 100000
- 保证爱丽丝与鲍勃的糖果总量不同。
- 答案肯定存在。
## 解题思路
- 两人交换糖果,使得两人糖果相等。要求输出一个数组,里面分别包含两人必须交换的糖果大小。
- 首先这一题肯定了一定有解其次只允许交换一次。有了这两个前提使本题变成简单题。先计算出为了使得交换以后两个相同的糖果数A 需要增加或者减少的糖果数 diff。然后遍历 B ,看 A 中是否存在一个元素,能使得 B 做了对应交换 diff 以后,两人糖果相等。(此题前提保证了一定能找到)。最后输出 A 中的这个元素和遍历到 B 的这个元素,即是两人要交换的糖果数。
## 代码
```go
func fairCandySwap(A []int, B []int) []int {
hDiff, aMap := diff(A, B)/2, make(map[int]int, len(A))
for _, a := range A {
aMap[a] = a
}
for _, b := range B {
if a, ok := aMap[hDiff+b]; ok {
return []int{a, b}
}
}
return nil
}
func diff(A []int, B []int) int {
diff, maxLen := 0, max(len(A), len(B))
for i := 0; i < maxLen; i++ {
if i < len(A) {
diff += A[i]
}
if i < len(B) {
diff -= B[i]
}
}
return diff
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```

View File

@ -0,0 +1,32 @@
package leetcode
func isMonotonic(A []int) bool {
if len(A) <= 1 {
return true
}
if A[0] < A[1] {
return inc(A[1:])
}
if A[0] > A[1] {
return dec(A[1:])
}
return inc(A[1:]) || dec(A[1:])
}
func inc(A []int) bool {
for i := 0; i < len(A)-1; i++ {
if A[i] > A[i+1] {
return false
}
}
return true
}
func dec(A []int) bool {
for i := 0; i < len(A)-1; i++ {
if A[i] < A[i+1] {
return false
}
}
return true
}

View File

@ -0,0 +1,67 @@
package leetcode
import (
"fmt"
"testing"
)
type question896 struct {
para896
ans896
}
// para 是参数
// one 代表第一个参数
type para896 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans896 struct {
one bool
}
func Test_Problem896(t *testing.T) {
qs := []question896{
question896{
para896{[]int{2, 1, 3}},
ans896{false},
},
question896{
para896{[]int{1, 2, 2, 3}},
ans896{true},
},
question896{
para896{[]int{6, 5, 4, 4}},
ans896{true},
},
question896{
para896{[]int{1, 3, 2}},
ans896{false},
},
question896{
para896{[]int{1, 2, 4, 5}},
ans896{true},
},
question896{
para896{[]int{1, 1, 1}},
ans896{true},
},
}
fmt.Printf("------------------------Leetcode Problem 896------------------------\n")
for _, q := range qs {
_, p := q.ans896, q.para896
fmt.Printf("【input】:%v 【output】:%v\n", p, isMonotonic(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,95 @@
# [896. Monotonic Array](https://leetcode.com/problems/monotonic-array/)
## 题目
An array is *monotonic* if it is either monotone increasing or monotone decreasing.
An array `A` is monotone increasing if for all `i <= j`, `A[i] <= A[j]`. An array `A` is monotone decreasing if for all `i <= j`, `A[i] >= A[j]`.
Return `true` if and only if the given array `A` is monotonic.
**Example 1**:
```
Input: [1,2,2,3]
Output: true
```
**Example 2**:
```
Input: [6,5,4,4]
Output: true
```
**Example 3**:
```
Input: [1,3,2]
Output: false
```
**Example 4**:
```
Input: [1,2,4,5]
Output: true
```
**Example 5**:
```
Input: [1,1,1]
Output: true
```
**Note**:
1. `1 <= A.length <= 50000`
2. `-100000 <= A[i] <= 100000`
## 题目大意
如果数组是单调递增或单调递减的,那么它是单调的。如果对于所有 i <= jA[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= jA[i]> = A[j],那么数组 A 是单调递减的。当给定的数组 A 是单调数组时返回 true否则返回 false。
## 解题思路
- 判断给定的数组是不是单调(单调递增或者单调递减)的。
- 简单题,按照题意循环判断即可。
## 代码
```go
func isMonotonic(A []int) bool {
if len(A) <= 1 {
return true
}
if A[0] < A[1] {
return inc(A[1:])
}
if A[0] > A[1] {
return dec(A[1:])
}
return inc(A[1:]) || dec(A[1:])
}
func inc(A []int) bool {
for i := 0; i < len(A)-1; i++ {
if A[i] > A[i+1] {
return false
}
}
return true
}
func dec(A []int) bool {
for i := 0; i < len(A)-1; i++ {
if A[i] < A[i+1] {
return false
}
}
return true
}
```

View File

@ -0,0 +1,26 @@
package leetcode
func hasGroupsSizeX(deck []int) bool {
if len(deck) < 2 {
return false
}
m, g := map[int]int{}, -1
for _, d := range deck {
m[d]++
}
for _, v := range m {
if g == -1 {
g = v
} else {
g = gcd(g, v)
}
}
return g >= 2
}
func gcd(a, b int) int {
if a == 0 {
return b
}
return gcd(b%a, a)
}

View File

@ -0,0 +1,62 @@
package leetcode
import (
"fmt"
"testing"
)
type question914 struct {
para914
ans914
}
// para 是参数
// one 代表第一个参数
type para914 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans914 struct {
one bool
}
func Test_Problem914(t *testing.T) {
qs := []question914{
question914{
para914{[]int{1, 2, 3, 4, 4, 3, 2, 1}},
ans914{true},
},
question914{
para914{[]int{1, 1, 1, 2, 2, 2, 3, 3}},
ans914{false},
},
question914{
para914{[]int{1}},
ans914{false},
},
question914{
para914{[]int{1, 1}},
ans914{true},
},
question914{
para914{[]int{1, 1, 2, 2, 2, 2}},
ans914{true},
},
}
fmt.Printf("------------------------Leetcode Problem 914------------------------\n")
for _, q := range qs {
_, p := q.ans914, q.para914
fmt.Printf("【input】:%v 【output】:%v\n", p, hasGroupsSizeX(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,105 @@
# [914. X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/)
## 题目
In a deck of cards, each card has an integer written on it.
Return `true` if and only if you can choose `X >= 2` such that it is possible to split the entire deck into 1 or more groups of cards, where:
- Each group has exactly `X` cards.
- All the cards in each group have the same integer.
**Example 1**:
```
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
```
**Example 2**:
```
Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.
```
**Example 3**:
```
Input: deck = [1]
Output: false
Explanation: No possible partition.
```
**Example 4**:
```
Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].
```
**Example 5**:
```
Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].
```
**Constraints**:
- `1 <= deck.length <= 10^4`
- `0 <= deck[i] < 10^4`
## 题目大意
给定一副牌,每张牌上都写着一个整数。此时,你需要选定一个数字 X使我们可以将整副牌按下述规则分成 1 组或更多组:
- 每组都有 X 张牌。
- 组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。
## 解题思路
- 给定一副牌,要求选出数字 X使得每组都有 X 张牌,每组牌的数字都相同。当 X ≥ 2 的时候,输出 true。
- 通过分析题目,我们可以知道,只有当 X 为所有 count 的约数,即所有 count 的最大公约数的约数时,才存在可能的分组。因此我们只要求出所有 count 的最大公约数 g判断 g 是否大于等于 2 即可,如果大于等于 2则满足条件否则不满足。
- 时间复杂度O(NlogC),其中 N 是卡牌的个数C 是数组 deck 中数的范围,在本题中 C 的值为 10000。求两个数最大公约数的复杂度是 O(logC),需要求最多 N - 1 次。空间复杂度O(N + C) 或 O(N)。
## 代码
```go
package leetcode
func hasGroupsSizeX(deck []int) bool {
if len(deck) < 2 {
return false
}
m, g := map[int]int{}, -1
for _, d := range deck {
m[d]++
}
for _, v := range m {
if g == -1 {
g = v
} else {
g = gcd(g, v)
}
}
return g >= 2
}
func gcd(a, b int) int {
if a == 0 {
return b
}
return gcd(b%a, a)
}
```

View File

@ -0,0 +1,21 @@
package leetcode
func sumEvenAfterQueries(A []int, queries [][]int) []int {
cur, res := 0, []int{}
for _, v := range A {
if v%2 == 0 {
cur += v
}
}
for _, q := range queries {
if A[q[1]]%2 == 0 {
cur -= A[q[1]]
}
A[q[1]] += q[0]
if A[q[1]]%2 == 0 {
cur += A[q[1]]
}
res = append(res, cur)
}
return res
}

View File

@ -0,0 +1,43 @@
package leetcode
import (
"fmt"
"testing"
)
type question985 struct {
para985
ans985
}
// para 是参数
// one 代表第一个参数
type para985 struct {
A []int
queries [][]int
}
// ans 是答案
// one 代表第一个答案
type ans985 struct {
one []int
}
func Test_Problem985(t *testing.T) {
qs := []question985{
question985{
para985{[]int{1, 2, 3, 4}, [][]int{[]int{1, 0}, []int{-3, 1}, []int{-4, 0}, []int{2, 3}}},
ans985{[]int{8, 6, 2, 4}},
},
}
fmt.Printf("------------------------Leetcode Problem 985------------------------\n")
for _, q := range qs {
_, p := q.ans985, q.para985
fmt.Printf("【input】:%v 【output】:%v\n\n\n", p, sumEvenAfterQueries(p.A, p.queries))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,68 @@
# [985. Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/)
## 题目
We have an array `A` of integers, and an array `queries` of queries.
For the `i`-th query `val = queries[i][0], index = queries[i][1]`, we add val to `A[index]`. Then, the answer to the `i`-th query is the sum of the even values of `A`.
*(Here, the given `index = queries[i][1]` is a 0-based index, and each query permanently modifies the array `A`.)*
Return the answer to all queries. Your `answer` array should have `answer[i]` as the answer to the `i`-th query.
**Example 1**:
```
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
```
**Note**:
1. `1 <= A.length <= 10000`
2. `-10000 <= A[i] <= 10000`
3. `1 <= queries.length <= 10000`
4. `-10000 <= queries[i][0] <= 10000`
5. `0 <= queries[i][1] < A.length`
## 题目大意
给出一个整数数组 A 和一个查询数组 queries。
对于第 i 次查询 val = queries[i][0], index = queries[i][1]我们会把 val 加到 A[index] 上。然后 i 次查询的答案是 A 中偶数值的和。此处给定的 index = queries[i][1] 是从 0 开始的索引每次查询都会永久修改数组 A。返回所有查询的答案。你的答案应当以数组 answer 给出answer[i] 为第 i 次查询的答案。
## 解题思路
- 给出一个数组 A 和 query 数组。要求每次 query 操作都改变数组 A 中的元素值,并计算此次操作结束数组 A 中偶数值之和。
- 简单题,先计算 A 中所有偶数之和。再每次 query 操作的时候,动态维护这个偶数之和即可。
## 代码
```go
func sumEvenAfterQueries(A []int, queries [][]int) []int {
cur, res := 0, []int{}
for _, v := range A {
if v%2 == 0 {
cur += v
}
}
for _, q := range queries {
if A[q[1]]%2 == 0 {
cur -= A[q[1]]
}
A[q[1]] += q[0]
if A[q[1]]%2 == 0 {
cur += A[q[1]]
}
res = append(res, cur)
}
return res
}
```

View File

@ -0,0 +1,27 @@
package leetcode
func numRookCaptures(board [][]byte) int {
num := 0
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == 'R' {
num += caputure(board, i-1, j, -1, 0) // Up
num += caputure(board, i+1, j, 1, 0) // Down
num += caputure(board, i, j-1, 0, -1) // Left
num += caputure(board, i, j+1, 0, 1) // Right
}
}
}
return num
}
func caputure(board [][]byte, x, y int, bx, by int) int {
for x >= 0 && x < len(board) && y >= 0 && y < len(board[x]) && board[x][y] != 'B' {
if board[x][y] == 'p' {
return 1
}
x += bx
y += by
}
return 0
}

View File

@ -0,0 +1,79 @@
package leetcode
import (
"fmt"
"testing"
)
type question999 struct {
para999
ans999
}
// para 是参数
// one 代表第一个参数
type para999 struct {
one [][]byte
}
// ans 是答案
// one 代表第一个答案
type ans999 struct {
one int
}
func Test_Problem999(t *testing.T) {
qs := []question999{
question999{
para999{[][]byte{
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', 'p', 'p', 'p', 'p', 'p', '.', '.'},
[]byte{'.', 'p', 'p', 'B', 'p', 'p', '.', '.'},
[]byte{'.', 'p', 'B', 'R', 'B', 'p', '.', '.'},
[]byte{'.', 'p', 'p', 'B', 'p', 'p', '.', '.'},
[]byte{'.', 'p', 'p', 'p', 'p', 'p', '.', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
}},
ans999{0},
},
question999{
para999{[][]byte{
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'p', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'R', '.', '.', '.', 'p'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'p', '.', '.', '.', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
}},
ans999{3},
},
question999{
para999{[][]byte{
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'p', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'p', '.', '.', '.', '.'},
[]byte{'p', 'p', '.', 'R', '.', 'p', 'B', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'B', '.', '.', '.', '.'},
[]byte{'.', '.', '.', 'p', '.', '.', '.', '.'},
[]byte{'.', '.', '.', '.', '.', '.', '.', '.'},
}},
ans999{3},
},
}
fmt.Printf("------------------------Leetcode Problem 999------------------------\n")
for _, q := range qs {
_, p := q.ans999, q.para999
fmt.Printf("【input】:%v 【output】:%v\n", p, numRookCaptures(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,97 @@
# [999. Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook/)
## 题目
On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.
Return the number of pawns the rook can capture in one move.
**Example 1**:
![https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG](https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG)
```
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
In this example the rook is able to capture all the pawns.
```
**Example 2**:
![https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG](https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG)
```
Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation:
Bishops are blocking the rook to capture any pawn.
```
**Example 3**:
![https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG](https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG)
```
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
The rook can capture the pawns at positions b5, d6 and f5.
```
**Note**:
1. `board.length == board[i].length == 8`
2. `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
3. There is exactly one cell with `board[i][j] == 'R'`
## 题目大意
在一个 8 x 8 的棋盘上有一个白色的车Rook用字符 'R' 表示。棋盘上还可能存在空方块白色的象Bishop以及黑色的卒pawn分别用字符 '.''B' 和 'p' 表示。不难看出,大写字符表示的是白棋,小写字符表示的是黑棋。车按国际象棋中的规则移动。东,西,南,北四个基本方向任选其一,然后一直向选定的方向移动,直到满足下列四个条件之一:
- 棋手选择主动停下来。
- 棋子因到达棋盘的边缘而停下。
- 棋子移动到某一方格来捕获位于该方格上敌方(黑色)的卒,停在该方格内。
- 车不能进入/越过已经放有其他友方棋子(白色的象)的方格,停在友方棋子前。
你现在可以控制车移动一次,请你统计有多少敌方的卒处于你的捕获范围内(即,可以被一步捕获的棋子数)。
## 解题思路
- 按照国际象棋的规则移动车,要求输出只移动一次,有多少个卒在车的捕获范围之内
- 简单题,按照国际象棋车的移动规则, 4 个方向分别枚举即可。
## 代码
```go
package leetcode
func numRookCaptures(board [][]byte) int {
num := 0
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == 'R' {
num += caputure(board, i-1, j, -1, 0) // Up
num += caputure(board, i+1, j, 1, 0) // Down
num += caputure(board, i, j-1, 0, -1) // Left
num += caputure(board, i, j+1, 0, 1) // Right
}
}
}
return num
}
func caputure(board [][]byte, x, y int, bx, by int) int {
for x >= 0 && x < len(board) && y >= 0 && y < len(board[x]) && board[x][y] != 'B' {
if board[x][y] == 'p' {
return 1
}
x += bx
y += by
}
return 0
}
```

View File

@ -0,0 +1,15 @@
package leetcode
import "sort"
func heightChecker(heights []int) int {
result, checker := 0, []int{}
checker = append(checker, heights...)
sort.Ints(checker)
for i := 0; i < len(heights); i++ {
if heights[i] != checker[i] {
result++
}
}
return result
}

View File

@ -0,0 +1,57 @@
package leetcode
import (
"fmt"
"testing"
)
type question1051 struct {
para1051
ans1051
}
// para 是参数
// one 代表第一个参数
type para1051 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1051 struct {
one int
}
func Test_Problem1051(t *testing.T) {
qs := []question1051{
question1051{
para1051{[]int{1, 1, 4, 2, 1, 3}},
ans1051{3},
},
question1051{
para1051{[]int{5, 1, 2, 3, 4}},
ans1051{5},
},
question1051{
para1051{[]int{1, 2, 3, 4, 5}},
ans1051{0},
},
question1051{
para1051{[]int{5, 4, 3, 2, 1}},
ans1051{4},
},
}
fmt.Printf("------------------------Leetcode Problem 1051------------------------\n")
for _, q := range qs {
_, p := q.ans1051, q.para1051
fmt.Printf("【input】:%v 【output】:%v\n", p, heightChecker(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,68 @@
# [1051. Height Checker](https://leetcode.com/problems/height-checker/)
## 题目
Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.
Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.
**Example 1**:
```
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
Current array : [1,1,4,2,1,3]
Target array : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.
```
**Example 2**:
```
Input: heights = [5,1,2,3,4]
Output: 5
```
**Example 3**:
```
Input: heights = [1,2,3,4,5]
Output: 0
```
**Constraints**:
- `1 <= heights.length <= 100`
- `1 <= heights[i] <= 100`
## 题目大意
学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。注意,当一组学生被选中时,他们之间可以以任何可能的方式重新排序,而未被选中的学生应该保持不动。
## 解题思路
- 给定一个高度数组,要求输出把这个数组按照非递减高度排列所需移动的最少次数。
- 简单题,最少次数意味着每次移动,一步到位,一步就移动到它所在的最终位置。那么用一个辅助排好序的数组,一一比对计数即可。
## 代码
```go
func heightChecker(heights []int) int {
result, checker := 0, []int{}
checker = append(checker, heights...)
sort.Ints(checker)
for i := 0; i < len(heights); i++ {
if heights[i] != checker[i] {
result++
}
}
return result
}
```

View File

@ -0,0 +1,10 @@
package leetcode
func duplicateZeros(arr []int) {
for i := 0; i < len(arr); i++ {
if arr[i] == 0 && i+1 < len(arr) {
arr = append(arr[:i+1], arr[i:len(arr)-1]...)
i++
}
}
}

View File

@ -0,0 +1,54 @@
package leetcode
import (
"fmt"
"testing"
)
type question1089 struct {
para1089
ans1089
}
// para 是参数
// one 代表第一个参数
type para1089 struct {
arr []int
}
// ans 是答案
// one 代表第一个答案
type ans1089 struct {
}
func Test_Problem1089(t *testing.T) {
qs := []question1089{
question1089{
para1089{[]int{1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0}},
ans1089{},
},
question1089{
para1089{[]int{1, 0, 2, 3, 0, 4, 5, 0}},
ans1089{},
},
question1089{
para1089{[]int{1, 2, 3}},
ans1089{},
},
}
fmt.Printf("------------------------Leetcode Problem 1089------------------------\n")
for _, q := range qs {
_, p := q.ans1089, q.para1089
fmt.Printf("【input】:%v ", p)
duplicateZeros(p.arr)
fmt.Printf("【output】:%v \n", p.arr)
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,54 @@
# [1089. Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/)
## 题目
Given a fixed length array `arr` of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array **in place**, do not return anything from your function.
**Example 1**:
```
Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
```
**Example 2**:
```
Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]
```
**Note**:
1. `1 <= arr.length <= 10000`
2. `0 <= arr[i] <= 9`
## 题目大意
给你一个长度固定的整数数组 arr请你将该数组中出现的每个零都复写一遍并将其余的元素向右平移。注意请不要在超过该数组长度的位置写入元素。要求请对输入的数组 就地 进行上述修改不要从函数返回任何东西。
## 解题思路
- 给一个固定长度的数组,把数组元素为 0 的元素都往后复制一遍,后面的元素往后移,超出数组长度的部分删除。
- 简单题,按照题意,用 append 和 slice 操作即可。
## 代码
```go
func duplicateZeros(arr []int) {
for i := 0; i < len(arr); i++ {
if arr[i] == 0 && i+1 < len(arr) {
arr = append(arr[:i+1], arr[i:len(arr)-1]...)
i++
}
}
}
```

View File

@ -0,0 +1,19 @@
package leetcode
func shiftGrid(grid [][]int, k int) [][]int {
x, y := len(grid[0]), len(grid)
newGrid := make([][]int, y)
for i := 0; i < y; i++ {
newGrid[i] = make([]int, x)
}
for i := 0; i < y; i++ {
for j := 0; j < x; j++ {
ny := (k / x) + i
if (j + (k % x)) >= x {
ny++
}
newGrid[ny%y][(j+(k%x))%x] = grid[i][j]
}
}
return newGrid
}

View File

@ -0,0 +1,59 @@
package leetcode
import (
"fmt"
"testing"
)
type question1260 struct {
para1260
ans1260
}
// para 是参数
// one 代表第一个参数
type para1260 struct {
grid [][]int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1260 struct {
one [][]int
}
func Test_Problem1260(t *testing.T) {
qs := []question1260{
question1260{
para1260{[][]int{[]int{3, 7, 8}, []int{9, 11, 13}, []int{15, 16, 17}}, 2},
ans1260{[][]int{[]int{16, 17, 3}, []int{7, 8, 9}, []int{11, 13, 15}}},
},
question1260{
para1260{[][]int{[]int{1, 10, 4, 2}, []int{9, 3, 8, 7}, []int{15, 16, 17, 12}}, 10},
ans1260{[][]int{[]int{4, 2, 9, 3}, []int{8, 7, 15, 16}, []int{17, 12, 1, 10}}},
},
question1260{
para1260{[][]int{[]int{3, 8, 1, 9}, []int{19, 7, 2, 5}, []int{4, 6, 11, 10}, []int{12, 0, 21, 13}}, 4},
ans1260{[][]int{[]int{12, 0, 21, 13}, []int{3, 8, 1, 9}, []int{19, 7, 2, 5}, []int{4, 6, 11, 10}}},
},
question1260{
para1260{[][]int{[]int{1, 2, 3}, []int{4, 5, 6}, []int{7, 8, 9}}, 9},
ans1260{[][]int{[]int{1, 2, 3}, []int{4, 5, 6}, []int{7, 8, 9}}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 1260------------------------\n")
for _, q := range qs {
_, p := q.ans1260, q.para1260
fmt.Printf("【input】:%v 【output】:%v\n", p, shiftGrid(p.grid, p.k))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,86 @@
# [1260. Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/)
## 题目
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
- Element at `grid[i][j]` moves to `grid[i][j + 1]`.
- Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
- Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the *2D grid* after applying shift operation `k` times.
**Example 1**:
![https://assets.leetcode.com/uploads/2019/11/05/e1.png](https://assets.leetcode.com/uploads/2019/11/05/e1.png)
```
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
```
**Example 2**:
![https://assets.leetcode.com/uploads/2019/11/05/e2.png](https://assets.leetcode.com/uploads/2019/11/05/e2.png)
```
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
```
**Example 3**:
```
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
```
**Constraints**:
- `m == grid.length`
- `n == grid[i].length`
- `1 <= m <= 50`
- `1 <= n <= 50`
- `-1000 <= grid[i][j] <= 1000`
- `0 <= k <= 100`
## 题目大意
给你一个 m 行 n 列的二维网格 grid 和一个整数 k。你需要将 grid 迁移 k 次。每次「迁移」操作将会引发下述活动
- 位于 grid[i][j] 的元素将会移动到 grid[i][j + 1]。
- 位于 grid[i][n - 1] 的元素将会移动到 grid[i + 1][0]。
- 位于 grid[m - 1][n - 1] 的元素将会移动到 grid[0][0]。
请你返回 k 次迁移操作后最终得到的 二维网格。
## 解题思路
- 给一个矩阵和一个移动步数 k要求把矩阵每个元素往后移动 k 步,最后的元素移动头部,循环移动,最后输出移动结束的矩阵。
- 简单题,按照题意循环移动即可,注意判断边界情况。
## 代码
```go
func shiftGrid(grid [][]int, k int) [][]int {
x, y := len(grid[0]), len(grid)
newGrid := make([][]int, y)
for i := 0; i < y; i++ {
newGrid[i] = make([]int, x)
}
for i := 0; i < y; i++ {
for j := 0; j < x; j++ {
ny := (k / x) + i
if (j + (k % x)) >= x {
ny++
}
newGrid[ny%y][(j+(k%x))%x] = grid[i][j]
}
}
return newGrid
}
```

View File

@ -0,0 +1,42 @@
package leetcode
func tictactoe(moves [][]int) string {
board := [3][3]byte{}
for i := 0; i < len(moves); i++ {
if i%2 == 0 {
board[moves[i][0]][moves[i][1]] = 'X'
} else {
board[moves[i][0]][moves[i][1]] = 'O'
}
}
for i := 0; i < 3; i++ {
if board[i][0] == 'X' && board[i][1] == 'X' && board[i][2] == 'X' {
return "A"
}
if board[i][0] == 'O' && board[i][1] == 'O' && board[i][2] == 'O' {
return "B"
}
if board[0][i] == 'X' && board[1][i] == 'X' && board[2][i] == 'X' {
return "A"
}
if board[0][i] == 'O' && board[1][i] == 'O' && board[2][i] == 'O' {
return "B"
}
}
if board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X' {
return "A"
}
if board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O' {
return "B"
}
if board[0][2] == 'X' && board[1][1] == 'X' && board[2][0] == 'X' {
return "A"
}
if board[0][2] == 'O' && board[1][1] == 'O' && board[2][0] == 'O' {
return "B"
}
if len(moves) < 9 {
return "Pending"
}
return "Draw"
}

View File

@ -0,0 +1,57 @@
package leetcode
import (
"fmt"
"testing"
)
type question1275 struct {
para1275
ans1275
}
// para 是参数
// one 代表第一个参数
type para1275 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1275 struct {
one string
}
func Test_Problem1275(t *testing.T) {
qs := []question1275{
question1275{
para1275{[][]int{[]int{0, 0}, []int{2, 0}, []int{1, 1}, []int{2, 1}, []int{2, 2}}},
ans1275{"A"},
},
question1275{
para1275{[][]int{[]int{0, 0}, []int{1, 1}, []int{0, 1}, []int{0, 2}, []int{1, 0}, []int{2, 0}}},
ans1275{"B"},
},
question1275{
para1275{[][]int{[]int{0, 0}, []int{1, 1}, []int{2, 0}, []int{1, 0}, []int{1, 2}, []int{2, 1}, []int{0, 1}, []int{0, 2}, []int{2, 2}}},
ans1275{"Draw"},
},
question1275{
para1275{[][]int{[]int{0, 0}, []int{1, 1}}},
ans1275{"Pending"},
},
}
fmt.Printf("------------------------Leetcode Problem 1275------------------------\n")
for _, q := range qs {
_, p := q.ans1275, q.para1275
fmt.Printf("【input】:%v 【output】:%v\n", p, tictactoe(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,150 @@
# [1275. Find Winner on a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/)
## 题目
Tic-tac-toe is played by two players *A* and *B* on a 3 x 3 grid.
Here are the rules of Tic-Tac-Toe:
- Players take turns placing characters into empty squares (" ").
- The first player *A* always places "X" characters, while the second player *B* always places "O" characters.
- "X" and "O" characters are always placed into empty squares, never on filled ones.
- The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
- The game also ends if all squares are non-empty.
- No more moves can be played if the game is over.
Given an array `moves` where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which *A* and *B* play.
Return the winner of the game if it exists (*A* or *B*), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".
You can assume that `moves` is **valid** (It follows the rules of Tic-Tac-Toe), the grid is initially empty and *A* will play **first**.
**Example 1**:
```
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X " "X " "X " "X " "X "
" " -> " " -> " X " -> " X " -> " X "
" " "O " "O " "OO " "OOX"
```
**Example 2**:
```
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X " "X " "XX " "XXO" "XXO" "XXO"
" " -> " O " -> " O " -> " O " -> "XO " -> "XO "
" " " " " " " " " " "O "
```
**Example 3**:
```
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"
```
**Example 4**:
```
Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X "
" O "
" "
```
**Constraints:**
- `1 <= moves.length <= 9`
- `moves[i].length == 2`
- `0 <= moves[i][j] <= 2`
- There are no repeated elements on `moves`.
- `moves` follow the rules of tic tac toe.
## 题目大意
A 和 B 在一个 3 x 3 的网格上玩井字棋。井字棋游戏的规则如下
- 玩家轮流将棋子放在空方格 (" ") 上。
- 第一个玩家 A 总是用 "X" 作为棋子,而第二个玩家 B 总是用 "O" 作为棋子。
- "X" 和 "O" 只能放在空方格中,而不能放在已经被占用的方格上。
- 只要有 3 个相同的(非空)棋子排成一条直线(行、列、对角线)时,游戏结束。
- 如果所有方块都放满棋子(不为空),游戏也会结束。
- 游戏结束后,棋子无法再进行任何移动。
给你一个数组 moves其中每个元素是大小为 2 的另一个数组(元素分别对应网格的行和列),它按照 A 和 B 的行动顺序(先 A 后 B记录了两人各自的棋子位置。如果游戏存在获胜者A 或 B就返回该游戏的获胜者如果游戏以平局结束则返回 "Draw";如果仍会有行动(游戏未结束),则返回 "Pending"。你可以假设 moves 都 有效遵循井字棋规则网格最初是空的A 将先行动。
提示:
- 1 <= moves.length <= 9
- moves[i].length == 2
- 0 <= moves[i][j] <= 2
- moves 里没有重复的元素。
- moves 遵循井字棋的规则。
## 解题思路
- 两人玩 3*3 井字棋A 先走B 再走。谁能获胜就输出谁,如果平局输出 “Draw”如果游戏还未结束输出 “Pending”。游戏规则谁能先占满行、列或者对角线任意一条线谁就赢。
- 简单题。题目给定 move 数组最多 3 步,而要赢得比赛,必须走满 3 步,所以可以先模拟,按照给的步数数组把 A 和 B 的步数都放在棋盘上。然后依次判断行、列,对角线的三种情况。如果都判完了,剩下的情况就是平局和死局的情况。
## 代码
```go
func tictactoe(moves [][]int) string {
board := [3][3]byte{}
for i := 0; i < len(moves); i++ {
if i%2 == 0 {
board[moves[i][0]][moves[i][1]] = 'X'
} else {
board[moves[i][0]][moves[i][1]] = 'O'
}
}
for i := 0; i < 3; i++ {
if board[i][0] == 'X' && board[i][1] == 'X' && board[i][2] == 'X' {
return "A"
}
if board[i][0] == 'O' && board[i][1] == 'O' && board[i][2] == 'O' {
return "B"
}
if board[0][i] == 'X' && board[1][i] == 'X' && board[2][i] == 'X' {
return "A"
}
if board[0][i] == 'O' && board[1][i] == 'O' && board[2][i] == 'O' {
return "B"
}
}
if board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X' {
return "A"
}
if board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O' {
return "B"
}
if board[0][2] == 'X' && board[1][1] == 'X' && board[2][0] == 'X' {
return "A"
}
if board[0][2] == 'O' && board[1][1] == 'O' && board[2][0] == 'O' {
return "B"
}
if len(moves) < 9 {
return "Pending"
}
return "Draw"
}
```

View File

@ -0,0 +1,27 @@
package leetcode
func luckyNumbers(matrix [][]int) []int {
t, r, res := make([]int, len(matrix[0])), make([]int, len(matrix[0])), []int{}
for _, val := range matrix {
m, k := val[0], 0
for j := 0; j < len(matrix[0]); j++ {
if val[j] < m {
m = val[j]
k = j
}
if t[j] < val[j] {
t[j] = val[j]
}
}
if t[k] == m {
r[k] = m
}
}
for k, v := range r {
if v > 0 && v == t[k] {
res = append(res, v)
}
}
return res
}

View File

@ -0,0 +1,58 @@
package leetcode
import (
"fmt"
"testing"
)
type question1380 struct {
para1380
ans1380
}
// para 是参数
// one 代表第一个参数
type para1380 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1380 struct {
one []int
}
func Test_Problem1380(t *testing.T) {
qs := []question1380{
question1380{
para1380{[][]int{[]int{3, 7, 8}, []int{9, 11, 13}, []int{15, 16, 17}}},
ans1380{[]int{15}},
},
question1380{
para1380{[][]int{[]int{1, 10, 4, 2}, []int{9, 3, 8, 7}, []int{15, 16, 17, 12}}},
ans1380{[]int{12}},
},
question1380{
para1380{[][]int{[]int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}}},
ans1380{[]int{1}},
},
question1380{
para1380{[][]int{[]int{7, 8}, []int{1, 2}}},
ans1380{[]int{7}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 1380------------------------\n")
for _, q := range qs {
_, p := q.ans1380, q.para1380
fmt.Printf("【input】:%v 【output】:%v\n", p, luckyNumbers(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,83 @@
# [1380. Lucky Numbers in a Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix/)
## 题目
Given a `m * n` matrix of **distinct** numbers, return all lucky numbers in the matrix in **any** order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1**:
```
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column
```
**Example 2**:
```
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
```
**Example 3**:
```
Input: matrix = [[7,8],[1,2]]
Output: [7]
```
**Constraints**:
- `m == mat.length`
- `n == mat[i].length`
- `1 <= n, m <= 50`
- `1 <= matrix[i][j] <= 10^5`.
- All elements in the matrix are distinct.
## 题目大意
给你一个 m * n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。幸运数是指矩阵中满足同时下列两个条件的元素:
- 在同一行的所有元素中最小
- 在同一列的所有元素中最大
## 解题思路
- 找出矩阵中的幸运数。幸运数的定义:同时满足 2 个条件,在同一行的所有元素中最小并且在同一列的所有元素中最大。
- 简单题。按照题意遍历矩阵,找到同时满足 2 个条件的数输出即可。
## 代码
```go
func luckyNumbers(matrix [][]int) []int {
t, r, res := make([]int, len(matrix[0])), make([]int, len(matrix[0])), []int{}
for _, val := range matrix {
m, k := val[0], 0
for j := 0; j < len(matrix[0]); j++ {
if val[j] < m {
m = val[j]
k = j
}
if t[j] < val[j] {
t[j] = val[j]
}
}
if t[k] == m {
r[k] = m
}
}
for k, v := range r {
if v > 0 && v == t[k] {
res = append(res, v)
}
}
return res
}
```

View File

@ -0,0 +1,23 @@
package leetcode
func findTheDistanceValue(arr1 []int, arr2 []int, d int) int {
res := 0
for i := range arr1 {
for j := range arr2 {
if abs(arr1[i]-arr2[j]) <= d {
break
}
if j == len(arr2)-1 {
res++
}
}
}
return res
}
func abs(a int) int {
if a < 0 {
return -1 * a
}
return a
}

View File

@ -0,0 +1,55 @@
package leetcode
import (
"fmt"
"testing"
)
type question1385 struct {
para1385
ans1385
}
// para 是参数
// one 代表第一个参数
type para1385 struct {
arr1 []int
arr2 []int
d int
}
// ans 是答案
// one 代表第一个答案
type ans1385 struct {
one []int
}
func Test_Problem1385(t *testing.T) {
qs := []question1385{
question1385{
para1385{[]int{4, 5, 8}, []int{10, 9, 1, 8}, 2},
ans1385{[]int{2}},
},
question1385{
para1385{[]int{1, 4, 2, 3}, []int{-4, -3, 6, 10, 20, 30}, 3},
ans1385{[]int{2}},
},
question1385{
para1385{[]int{2, 1, 100, 3}, []int{-5, -2, 10, -3, 7}, 6},
ans1385{[]int{1}},
},
}
fmt.Printf("------------------------Leetcode Problem 1385------------------------\n")
for _, q := range qs {
_, p := q.ans1385, q.para1385
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", findTheDistanceValue(p.arr1, p.arr2, p.d))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,94 @@
# [1385. Find the Distance Value Between Two Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays/)
## 题目
Given two integer arrays `arr1` and `arr2`, and the integer `d`, *return the distance value between the two arrays*.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1**:
```
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2
```
**Example 2**:
```
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2
```
**Example 3**:
```
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
```
**Constraints**:
- `1 <= arr1.length, arr2.length <= 500`
- `-10^3 <= arr1[i], arr2[j] <= 10^3`
- `0 <= d <= 100`
## 题目大意
给你两个整数数组 arr1  arr2 和一个整数 d 请你返回两个数组之间的 距离值 。「距离值」 定义为符合此距离要求的元素数目对于元素 arr1[i] 不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d 。
提示:
- 1 <= arr1.length, arr2.length <= 500
- -10^3 <= arr1[i], arr2[j] <= 10^3
- 0 <= d <= 100
## 解题思路
- 计算两个数组之间的距离,距离值的定义:满足对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d 这一条件的元素数目。
- 简单题,按照距离值的定义,双层循环计数即可。
## 代码
```go
func findTheDistanceValue(arr1 []int, arr2 []int, d int) int {
res := 0
for i := range arr1 {
for j := range arr2 {
if abs(arr1[i]-arr2[j]) <= d {
break
}
if j == len(arr2)-1 {
res++
}
}
}
return res
}
func abs(a int) int {
if a < 0 {
return -1 * a
}
return a
}
```

View File

@ -0,0 +1,10 @@
package leetcode
func createTargetArray(nums []int, index []int) []int {
result := make([]int, len(nums))
for i, pos := range index {
copy(result[pos+1:i+1], result[pos:i])
result[pos] = nums[i]
}
return result
}

View File

@ -0,0 +1,54 @@
package leetcode
import (
"fmt"
"testing"
)
type question1389 struct {
para1389
ans1389
}
// para 是参数
// one 代表第一个参数
type para1389 struct {
nums []int
index []int
}
// ans 是答案
// one 代表第一个答案
type ans1389 struct {
one []int
}
func Test_Problem1389(t *testing.T) {
qs := []question1389{
question1389{
para1389{[]int{0, 1, 2, 3, 4}, []int{0, 1, 2, 2, 1}},
ans1389{[]int{0, 4, 1, 3, 2}},
},
question1389{
para1389{[]int{1, 2, 3, 4, 0}, []int{0, 1, 2, 3, 0}},
ans1389{[]int{0, 1, 2, 3, 4}},
},
question1389{
para1389{[]int{1}, []int{0}},
ans1389{[]int{1}},
},
}
fmt.Printf("------------------------Leetcode Problem 1389------------------------\n")
for _, q := range qs {
_, p := q.ans1389, q.para1389
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", createTargetArray(p.nums, p.index))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,86 @@
# [1389. Create Target Array in the Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order/)
## 题目
Given two arrays of integers `nums` and `index`. Your task is to create *target* array under the following rules:
- Initially *target* array is empty.
- From left to right read nums[i] and index[i], insert at index `index[i]` the value `nums[i]` in *target* array.
- Repeat the previous step until there are no elements to read in `nums` and `index.`
Return the *target* array.
It is guaranteed that the insertion operations will be valid.
**Example 1**:
```
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
```
**Example 2**:
```
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]
```
**Example 3**:
```
Input: nums = [1], index = [0]
Output: [1]
```
**Constraints**:
- `1 <= nums.length, index.length <= 100`
- `nums.length == index.length`
- `0 <= nums[i] <= 100`
- `0 <= index[i] <= i`
## 题目大意
给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组
- 目标数组 target 最初为空。
- 按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。
- 重复上一步,直到在 nums 和 index 中都没有要读取的元素。
请你返回目标数组。题目保证数字插入位置总是存在。
## 解题思路
- 给定 2 个数组,分别装的是待插入的元素和待插入的位置。最后输出操作完成的数组。
- 简单题,按照题意插入元素即可。
## 代码
```go
func createTargetArray(nums []int, index []int) []int {
result := make([]int, len(nums))
for i, pos := range index {
copy(result[pos+1:i+1], result[pos:i])
result[pos] = nums[i]
}
return result
}
```

View File

@ -0,0 +1,57 @@
# [448. Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)
## 题目
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
**Example**:
```
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
```
## 题目大意
给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。找到所有在 [1, n] 范围之间没有出现在数组中的数字。你能在不使用额外空间且时间复杂度为 O(n) 的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
## 解题思路
- 找出 [1,n] 范围内没有出现在数组中的数字。要求不使用额外空间,并且时间复杂度为 O(n)。
- 要求不能使用额外的空间,那么只能想办法在原有数组上进行修改,并且这个修改是可还原的。时间复杂度也只能允许我们一层循环。只要循环一次能标记出已经出现过的数字,这道题就可以按要求解答出来。这里笔者的标记方法是把 |nums[i]|-1 索引位置的元素标记为负数。即 nums[| nums[i] |- 1] * -1。这里需要注意的是nums[i] 需要加绝对值,因为它可能被之前的数置为负数了,需要还原一下。最后再遍历一次数组,若当前数组元素 nums[i] 为负数,说明我们在数组中存在数字 i+1。把结果输出到最终数组里即可。
## 代码
```go
package leetcode
func findDisappearedNumbers(nums []int) []int {
res := []int{}
for _, v := range nums {
if v < 0 {
v = -v
}
if nums[v-1] > 0 {
nums[v-1] = -nums[v-1]
}
}
for i, v := range nums {
if v > 0 {
res = append(res, i+1)
}
}
return res
}
```

View File

@ -0,0 +1,59 @@
# [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)
## 题目
Given a binary array, find the maximum number of consecutive 1s in this array.
**Example 1**:
```
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
```
**Note**:
- The input array will only contain `0` and `1`.
- The length of input array is a positive integer and will not exceed 10,000
## 题目大意
给定一个二进制数组, 计算其中最大连续1的个数。
注意:
- 输入的数组只包含 0 和 1。
- 输入数组的长度是正整数,且不超过 10,000。
## 解题思路
- 给定一个二进制数组, 计算其中最大连续1的个数。
- 简单题。扫一遍数组,累计 1 的个数,动态维护最大的计数,最终输出即可。
## 代码
```go
package leetcode
func findMaxConsecutiveOnes(nums []int) int {
maxCount, currentCount := 0, 0
for _, v := range nums {
if v == 1 {
currentCount++
} else {
currentCount = 0
}
if currentCount > maxCount {
maxCount = currentCount
}
}
return maxCount
}
```

View File

@ -0,0 +1,111 @@
# [661. Image Smoother](https://leetcode.com/problems/image-smoother/)
## 题目
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
**Example 1**:
```
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
```
**Note**:
1. The value in the given matrix is in the range of [0, 255].
2. The length and width of the given matrix are in the range of [1, 150].
## 题目大意
包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) 平均灰度的计算是周围的8个单元和它本身的值求平均如果周围的单元格不足八个则尽可能多的利用它们。
注意:
- 给定矩阵中的整数范围为 [0, 255]。
- 矩阵的长和宽的范围均为 [1, 150]。
## 解题思路
- 将二维数组中的每个元素变为周围 9 个元素的平均值。
- 简单题,按照题意计算平均值即可。需要注意的是边界问题,四个角和边上的元素,这些点计算平均值的时候,计算平均值都不足 9 个元素。
## 代码
```go
package leetcode
func imageSmoother(M [][]int) [][]int {
res := make([][]int, len(M))
for i := range M {
res[i] = make([]int, len(M[0]))
}
for y := 0; y < len(M); y++ {
for x := 0; x < len(M[0]); x++ {
res[y][x] = smooth(x, y, M)
}
}
return res
}
func smooth(x, y int, M [][]int) int {
count, sum := 1, M[y][x]
// Check bottom
if y+1 < len(M) {
sum += M[y+1][x]
count++
}
// Check Top
if y-1 >= 0 {
sum += M[y-1][x]
count++
}
// Check left
if x-1 >= 0 {
sum += M[y][x-1]
count++
}
// Check Right
if x+1 < len(M[y]) {
sum += M[y][x+1]
count++
}
// Check Coners
// Top Left
if y-1 >= 0 && x-1 >= 0 {
sum += M[y-1][x-1]
count++
}
// Top Right
if y-1 >= 0 && x+1 < len(M[0]) {
sum += M[y-1][x+1]
count++
}
// Bottom Left
if y+1 < len(M) && x-1 >= 0 {
sum += M[y+1][x-1]
count++
}
//Bottom Right
if y+1 < len(M) && x+1 < len(M[0]) {
sum += M[y+1][x+1]
count++
}
return sum / count
}
```

View File

@ -0,0 +1,80 @@
# [697. Degree of an Array](https://leetcode.com/problems/degree-of-an-array/)
## 题目
Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`.
**Example 1**:
```
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
```
**Example 2**:
```
Input: [1,2,2,3,1,4,2]
Output: 6
```
**Note**:
- `nums.length` will be between 1 and 50,000.
- `nums[i]` will be an integer between 0 and 49,999.
## 题目大意
给定一个非空且只包含非负数的整数数组 nums, 数组的度的定义是指数组里任一元素出现频数的最大值。你的任务是找到与 nums 拥有相同大小的度的最短连续子数组返回其长度。
注意:
- nums.length 在 1 到 50,000 区间范围内。
- nums[i] 是一个在 0 到 49,999 范围内的整数。
## 解题思路
- 找一个与给定数组相同度的最短连续子数组,输出其长度。数组的度的定义是任一元素出现频数的最大值。
- 简单题。先统计各个元素的频次,并且动态维护最大频次和子数组的起始和终点位置。这里最短连续子数组有点“迷惑人”。这个最短子数组其实处理起来很简单。只需从前往后扫一遍,记录各个元素第一次出现的位置和最后一次出现的位置即是最短的连续子数组。然后在频次字典里面寻找和最大频次相同的所有解,有可能有多个子数组能满足题意,取出最短的输出即可。
## 代码
```go
package leetcode
func findShortestSubArray(nums []int) int {
frequency, maxFreq, smallest := map[int][]int{}, 0, len(nums)
for i, num := range nums {
if _, found := frequency[num]; !found {
frequency[num] = []int{1, i, i}
} else {
frequency[num][0]++
frequency[num][2] = i
}
if maxFreq < frequency[num][0] {
maxFreq = frequency[num][0]
}
}
for _, indices := range frequency {
if indices[0] == maxFreq {
if smallest > indices[2]-indices[1]+1 {
smallest = indices[2] - indices[1] + 1
}
}
}
return smallest
}
```

View File

@ -0,0 +1,110 @@
# [888. Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap/)
## 题目
Alice and Bob have candy bars of different sizes: `A[i]` is the size of the `i`-th bar of candy that Alice has, and `B[j]` is the size of the `j`-th bar of candy that Bob has.
Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (*The total amount of candy a person has is the sum of the sizes of candy bars they have*.)
Return an integer array `ans` where `ans[0]` is the size of the candy bar that Alice must exchange, and `ans[1]` is the size of the candy bar that Bob must exchange.
If there are multiple answers, you may return any one of them. It is guaranteed an answer exists.
**Example 1**:
```
Input: A = [1,1], B = [2,2]
Output: [1,2]
```
**Example 2**:
```
Input: A = [1,2], B = [2,3]
Output: [1,2]
```
**Example 3**:
```
Input: A = [2], B = [1,3]
Output: [2,3]
```
**Example 4**:
```
Input: A = [1,2,5], B = [2,4]
Output: [5,4]
```
**Note**:
- `1 <= A.length <= 10000`
- `1 <= B.length <= 10000`
- `1 <= A[i] <= 100000`
- `1 <= B[i] <= 100000`
- It is guaranteed that Alice and Bob have different total amounts of candy.
- It is guaranteed there exists an answer.
## 题目大意
爱丽丝和鲍勃有不同大小的糖果棒A[i] 是爱丽丝拥有的第 i 块糖的大小B[j] 是鲍勃拥有的第 j 块糖的大小。因为他们是朋友所以他们想交换一个糖果棒这样交换后他们都有相同的糖果总量。一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。返回一个整数数组 ans其中 ans[0] 是爱丽丝必须交换的糖果棒的大小ans[1] 是 Bob 必须交换的糖果棒的大小。如果有多个答案,你可以返回其中任何一个。保证答案存在。
提示:
- 1 <= A.length <= 10000
- 1 <= B.length <= 10000
- 1 <= A[i] <= 100000
- 1 <= B[i] <= 100000
- 保证爱丽丝与鲍勃的糖果总量不同。
- 答案肯定存在。
## 解题思路
- 两人交换糖果,使得两人糖果相等。要求输出一个数组,里面分别包含两人必须交换的糖果大小。
- 首先这一题肯定了一定有解其次只允许交换一次。有了这两个前提使本题变成简单题。先计算出为了使得交换以后两个相同的糖果数A 需要增加或者减少的糖果数 diff。然后遍历 B ,看 A 中是否存在一个元素,能使得 B 做了对应交换 diff 以后,两人糖果相等。(此题前提保证了一定能找到)。最后输出 A 中的这个元素和遍历到 B 的这个元素,即是两人要交换的糖果数。
## 代码
```go
package leetcode
func fairCandySwap(A []int, B []int) []int {
hDiff, aMap := diff(A, B)/2, make(map[int]int, len(A))
for _, a := range A {
aMap[a] = a
}
for _, b := range B {
if a, ok := aMap[hDiff+b]; ok {
return []int{a, b}
}
}
return nil
}
func diff(A []int, B []int) int {
diff, maxLen := 0, max(len(A), len(B))
for i := 0; i < maxLen; i++ {
if i < len(A) {
diff += A[i]
}
if i < len(B) {
diff -= B[i]
}
}
return diff
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```

View File

@ -0,0 +1,99 @@
# [896. Monotonic Array](https://leetcode.com/problems/monotonic-array/)
## 题目
An array is *monotonic* if it is either monotone increasing or monotone decreasing.
An array `A` is monotone increasing if for all `i <= j`, `A[i] <= A[j]`. An array `A` is monotone decreasing if for all `i <= j`, `A[i] >= A[j]`.
Return `true` if and only if the given array `A` is monotonic.
**Example 1**:
```
Input: [1,2,2,3]
Output: true
```
**Example 2**:
```
Input: [6,5,4,4]
Output: true
```
**Example 3**:
```
Input: [1,3,2]
Output: false
```
**Example 4**:
```
Input: [1,2,4,5]
Output: true
```
**Example 5**:
```
Input: [1,1,1]
Output: true
```
**Note**:
1. `1 <= A.length <= 50000`
2. `-100000 <= A[i] <= 100000`
## 题目大意
如果数组是单调递增或单调递减的,那么它是单调的。如果对于所有 i <= jA[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= jA[i]> = A[j],那么数组 A 是单调递减的。当给定的数组 A 是单调数组时返回 true否则返回 false。
## 解题思路
- 判断给定的数组是不是单调(单调递增或者单调递减)的。
- 简单题,按照题意循环判断即可。
## 代码
```go
package leetcode
func isMonotonic(A []int) bool {
if len(A) <= 1 {
return true
}
if A[0] < A[1] {
return inc(A[1:])
}
if A[0] > A[1] {
return dec(A[1:])
}
return inc(A[1:]) || dec(A[1:])
}
func inc(A []int) bool {
for i := 0; i < len(A)-1; i++ {
if A[i] > A[i+1] {
return false
}
}
return true
}
func dec(A []int) bool {
for i := 0; i < len(A)-1; i++ {
if A[i] < A[i+1] {
return false
}
}
return true
}
```

View File

@ -0,0 +1,105 @@
# [914. X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/)
## 题目
In a deck of cards, each card has an integer written on it.
Return `true` if and only if you can choose `X >= 2` such that it is possible to split the entire deck into 1 or more groups of cards, where:
- Each group has exactly `X` cards.
- All the cards in each group have the same integer.
**Example 1**:
```
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
```
**Example 2**:
```
Input: deck = [1,1,1,2,2,2,3,3]
Output: false´
Explanation: No possible partition.
```
**Example 3**:
```
Input: deck = [1]
Output: false
Explanation: No possible partition.
```
**Example 4**:
```
Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].
```
**Example 5**:
```
Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].
```
**Constraints**:
- `1 <= deck.length <= 10^4`
- `0 <= deck[i] < 10^4`
## 题目大意
给定一副牌,每张牌上都写着一个整数。此时,你需要选定一个数字 X使我们可以将整副牌按下述规则分成 1 组或更多组:
- 每组都有 X 张牌。
- 组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。
## 解题思路
- 给定一副牌,要求选出数字 X使得每组都有 X 张牌,每组牌的数字都相同。当 X ≥ 2 的时候,输出 true。
- 通过分析题目,我们可以知道,只有当 X 为所有 count 的约数,即所有 count 的最大公约数的约数时,才存在可能的分组。因此我们只要求出所有 count 的最大公约数 g判断 g 是否大于等于 2 即可,如果大于等于 2则满足条件否则不满足。
- 时间复杂度O(NlogC),其中 N 是卡牌的个数C 是数组 deck 中数的范围,在本题中 C 的值为 10000。求两个数最大公约数的复杂度是 O(logC),需要求最多 N - 1 次。空间复杂度O(N + C) 或 O(N)。
## 代码
```go
package leetcode
func hasGroupsSizeX(deck []int) bool {
if len(deck) < 2 {
return false
}
m, g := map[int]int{}, -1
for _, d := range deck {
m[d]++
}
for _, v := range m {
if g == -1 {
g = v
} else {
g = gcd(g, v)
}
}
return g >= 2
}
func gcd(a, b int) int {
if a == 0 {
return b
}
return gcd(b%a, a)
}
```

View File

@ -0,0 +1,72 @@
# [985. Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/)
## 题目
We have an array `A` of integers, and an array `queries` of queries.
For the `i`-th query `val = queries[i][0], index = queries[i][1]`, we add val to `A[index]`. Then, the answer to the `i`-th query is the sum of the even values of `A`.
*(Here, the given `index = queries[i][1]` is a 0-based index, and each query permanently modifies the array `A`.)*
Return the answer to all queries. Your `answer` array should have `answer[i]` as the answer to the `i`-th query.
**Example 1**:
```
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
```
**Note**:
1. `1 <= A.length <= 10000`
2. `-10000 <= A[i] <= 10000`
3. `1 <= queries.length <= 10000`
4. `-10000 <= queries[i][0] <= 10000`
5. `0 <= queries[i][1] < A.length`
## 题目大意
给出一个整数数组 A 和一个查询数组 queries。
对于第 i 次查询 val = queries[i][0], index = queries[i][1]我们会把 val 加到 A[index] 上。然后 i 次查询的答案是 A 中偶数值的和。此处给定的 index = queries[i][1] 是从 0 开始的索引每次查询都会永久修改数组 A。返回所有查询的答案。你的答案应当以数组 answer 给出answer[i] 为第 i 次查询的答案。
## 解题思路
- 给出一个数组 A 和 query 数组。要求每次 query 操作都改变数组 A 中的元素值,并计算此次操作结束数组 A 中偶数值之和。
- 简单题,先计算 A 中所有偶数之和。再每次 query 操作的时候,动态维护这个偶数之和即可。
## 代码
```go
package leetcode
func sumEvenAfterQueries(A []int, queries [][]int) []int {
cur, res := 0, []int{}
for _, v := range A {
if v%2 == 0 {
cur += v
}
}
for _, q := range queries {
if A[q[1]]%2 == 0 {
cur -= A[q[1]]
}
A[q[1]] += q[0]
if A[q[1]]%2 == 0 {
cur += A[q[1]]
}
res = append(res, cur)
}
return res
}
```

View File

@ -0,0 +1,99 @@
# [999. Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook/)
## 题目
On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.
Return the number of pawns the rook can capture in one move.
**Example 1**:
![https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG](https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG)
```
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
In this example the rook is able to capture all the pawns.
```
**Example 2**:
![https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG](https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG)
```
Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation:
Bishops are blocking the rook to capture any pawn.
```
**Example 3**:
![https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG](https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG)
```
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
The rook can capture the pawns at positions b5, d6 and f5.
```
**Note**:
1. `board.length == board[i].length == 8`
2. `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
3. There is exactly one cell with `board[i][j] == 'R'`
## 题目大意
在一个 8 x 8 的棋盘上有一个白色的车Rook用字符 'R' 表示。棋盘上还可能存在空方块白色的象Bishop以及黑色的卒pawn分别用字符 '.''B' 和 'p' 表示。不难看出,大写字符表示的是白棋,小写字符表示的是黑棋。车按国际象棋中的规则移动。东,西,南,北四个基本方向任选其一,然后一直向选定的方向移动,直到满足下列四个条件之一:
- 棋手选择主动停下来。
- 棋子因到达棋盘的边缘而停下。
- 棋子移动到某一方格来捕获位于该方格上敌方(黑色)的卒,停在该方格内。
- 车不能进入/越过已经放有其他友方棋子(白色的象)的方格,停在友方棋子前。
你现在可以控制车移动一次,请你统计有多少敌方的卒处于你的捕获范围内(即,可以被一步捕获的棋子数)。
## 解题思路
- 按照国际象棋的规则移动车,要求输出只移动一次,有多少个卒在车的捕获范围之内
- 简单题,按照国际象棋车的移动规则, 4 个方向分别枚举即可。
## 代码
```go
package leetcode
func numRookCaptures(board [][]byte) int {
num := 0
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == 'R' {
num += caputure(board, i-1, j, -1, 0) // Up
num += caputure(board, i+1, j, 1, 0) // Down
num += caputure(board, i, j-1, 0, -1) // Left
num += caputure(board, i, j+1, 0, 1) // Right
}
}
}
return num
}
func caputure(board [][]byte, x, y int, bx, by int) int {
for x >= 0 && x < len(board) && y >= 0 && y < len(board[x]) && board[x][y] != 'B' {
if board[x][y] == 'p' {
return 1
}
x += bx
y += by
}
return 0
}
```

View File

@ -0,0 +1,72 @@
# [1051. Height Checker](https://leetcode.com/problems/height-checker/)
## 题目
Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.
Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.
**Example 1**:
```
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
Current array : [1,1,4,2,1,3]
Target array : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.
```
**Example 2**:
```
Input: heights = [5,1,2,3,4]
Output: 5
```
**Example 3**:
```
Input: heights = [1,2,3,4,5]
Output: 0
```
**Constraints**:
- `1 <= heights.length <= 100`
- `1 <= heights[i] <= 100`
## 题目大意
学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。注意,当一组学生被选中时,他们之间可以以任何可能的方式重新排序,而未被选中的学生应该保持不动。
## 解题思路
- 给定一个高度数组,要求输出把这个数组按照非递减高度排列所需移动的最少次数。
- 简单题,最少次数意味着每次移动,一步到位,一步就移动到它所在的最终位置。那么用一个辅助排好序的数组,一一比对计数即可。
## 代码
```go
package leetcode
func heightChecker(heights []int) int {
result, checker := 0, []int{}
checker = append(checker, heights...)
sort.Ints(checker)
for i := 0; i < len(heights); i++ {
if heights[i] != checker[i] {
result++
}
}
return result
}
```

View File

@ -0,0 +1,58 @@
# [1089. Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/)
## 题目
Given a fixed length array `arr` of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array **in place**, do not return anything from your function.
**Example 1**:
```
Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
```
**Example 2**:
```
Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]
```
**Note**:
1. `1 <= arr.length <= 10000`
2. `0 <= arr[i] <= 9`
## 题目大意
给你一个长度固定的整数数组 arr请你将该数组中出现的每个零都复写一遍并将其余的元素向右平移。注意请不要在超过该数组长度的位置写入元素。要求请对输入的数组 就地 进行上述修改不要从函数返回任何东西。
## 解题思路
- 给一个固定长度的数组,把数组元素为 0 的元素都往后复制一遍,后面的元素往后移,超出数组长度的部分删除。
- 简单题,按照题意,用 append 和 slice 操作即可。
## 代码
```go
package leetcode
func duplicateZeros(arr []int) {
for i := 0; i < len(arr); i++ {
if arr[i] == 0 && i+1 < len(arr) {
arr = append(arr[:i+1], arr[i:len(arr)-1]...)
i++
}
}
}
```

View File

@ -0,0 +1,90 @@
# [1260. Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/)
## 题目
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
- Element at `grid[i][j]` moves to `grid[i][j + 1]`.
- Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
- Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the *2D grid* after applying shift operation `k` times.
**Example 1**:
![https://assets.leetcode.com/uploads/2019/11/05/e1.png](https://assets.leetcode.com/uploads/2019/11/05/e1.png)
```
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
```
**Example 2**:
![https://assets.leetcode.com/uploads/2019/11/05/e2.png](https://assets.leetcode.com/uploads/2019/11/05/e2.png)
```
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
```
**Example 3**:
```
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
```
**Constraints**:
- `m == grid.length`
- `n == grid[i].length`
- `1 <= m <= 50`
- `1 <= n <= 50`
- `-1000 <= grid[i][j] <= 1000`
- `0 <= k <= 100`
## 题目大意
给你一个 m 行 n 列的二维网格 grid 和一个整数 k。你需要将 grid 迁移 k 次。每次「迁移」操作将会引发下述活动
- 位于 grid[i][j] 的元素将会移动到 grid[i][j + 1]。
- 位于 grid[i][n - 1] 的元素将会移动到 grid[i + 1][0]。
- 位于 grid[m - 1][n - 1] 的元素将会移动到 grid[0][0]。
请你返回 k 次迁移操作后最终得到的 二维网格。
## 解题思路
- 给一个矩阵和一个移动步数 k要求把矩阵每个元素往后移动 k 步,最后的元素移动头部,循环移动,最后输出移动结束的矩阵。
- 简单题,按照题意循环移动即可,注意判断边界情况。
## 代码
```go
package leetcode
func shiftGrid(grid [][]int, k int) [][]int {
x, y := len(grid[0]), len(grid)
newGrid := make([][]int, y)
for i := 0; i < y; i++ {
newGrid[i] = make([]int, x)
}
for i := 0; i < y; i++ {
for j := 0; j < x; j++ {
ny := (k / x) + i
if (j + (k % x)) >= x {
ny++
}
newGrid[ny%y][(j+(k%x))%x] = grid[i][j]
}
}
return newGrid
}
```

View File

@ -0,0 +1,154 @@
# [1275. Find Winner on a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/)
## 题目
Tic-tac-toe is played by two players *A* and *B* on a 3 x 3 grid.
Here are the rules of Tic-Tac-Toe:
- Players take turns placing characters into empty squares (" ").
- The first player *A* always places "X" characters, while the second player *B* always places "O" characters.
- "X" and "O" characters are always placed into empty squares, never on filled ones.
- The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
- The game also ends if all squares are non-empty.
- No more moves can be played if the game is over.
Given an array `moves` where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which *A* and *B* play.
Return the winner of the game if it exists (*A* or *B*), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".
You can assume that `moves` is **valid** (It follows the rules of Tic-Tac-Toe), the grid is initially empty and *A* will play **first**.
**Example 1**:
```
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X " "X " "X " "X " "X "
" " -> " " -> " X " -> " X " -> " X "
" " "O " "O " "OO " "OOX"
```
**Example 2**:
```
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X " "X " "XX " "XXO" "XXO" "XXO"
" " -> " O " -> " O " -> " O " -> "XO " -> "XO "
" " " " " " " " " " "O "
```
**Example 3**:
```
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"
```
**Example 4**:
```
Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X "
" O "
" "
```
**Constraints:**
- `1 <= moves.length <= 9`
- `moves[i].length == 2`
- `0 <= moves[i][j] <= 2`
- There are no repeated elements on `moves`.
- `moves` follow the rules of tic tac toe.
## 题目大意
A 和 B 在一个 3 x 3 的网格上玩井字棋。井字棋游戏的规则如下
- 玩家轮流将棋子放在空方格 (" ") 上。
- 第一个玩家 A 总是用 "X" 作为棋子,而第二个玩家 B 总是用 "O" 作为棋子。
- "X" 和 "O" 只能放在空方格中,而不能放在已经被占用的方格上。
- 只要有 3 个相同的(非空)棋子排成一条直线(行、列、对角线)时,游戏结束。
- 如果所有方块都放满棋子(不为空),游戏也会结束。
- 游戏结束后,棋子无法再进行任何移动。
给你一个数组 moves其中每个元素是大小为 2 的另一个数组(元素分别对应网格的行和列),它按照 A 和 B 的行动顺序(先 A 后 B记录了两人各自的棋子位置。如果游戏存在获胜者A 或 B就返回该游戏的获胜者如果游戏以平局结束则返回 "Draw";如果仍会有行动(游戏未结束),则返回 "Pending"。你可以假设 moves 都 有效遵循井字棋规则网格最初是空的A 将先行动。
提示:
- 1 <= moves.length <= 9
- moves[i].length == 2
- 0 <= moves[i][j] <= 2
- moves 里没有重复的元素。
- moves 遵循井字棋的规则。
## 解题思路
- 两人玩 3*3 井字棋A 先走B 再走。谁能获胜就输出谁,如果平局输出 “Draw”如果游戏还未结束输出 “Pending”。游戏规则谁能先占满行、列或者对角线任意一条线谁就赢。
- 简单题。题目给定 move 数组最多 3 步,而要赢得比赛,必须走满 3 步,所以可以先模拟,按照给的步数数组把 A 和 B 的步数都放在棋盘上。然后依次判断行、列,对角线的三种情况。如果都判完了,剩下的情况就是平局和死局的情况。
## 代码
```go
package leetcode
func tictactoe(moves [][]int) string {
board := [3][3]byte{}
for i := 0; i < len(moves); i++ {
if i%2 == 0 {
board[moves[i][0]][moves[i][1]] = 'X'
} else {
board[moves[i][0]][moves[i][1]] = 'O'
}
}
for i := 0; i < 3; i++ {
if board[i][0] == 'X' && board[i][1] == 'X' && board[i][2] == 'X' {
return "A"
}
if board[i][0] == 'O' && board[i][1] == 'O' && board[i][2] == 'O' {
return "B"
}
if board[0][i] == 'X' && board[1][i] == 'X' && board[2][i] == 'X' {
return "A"
}
if board[0][i] == 'O' && board[1][i] == 'O' && board[2][i] == 'O' {
return "B"
}
}
if board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X' {
return "A"
}
if board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O' {
return "B"
}
if board[0][2] == 'X' && board[1][1] == 'X' && board[2][0] == 'X' {
return "A"
}
if board[0][2] == 'O' && board[1][1] == 'O' && board[2][0] == 'O' {
return "B"
}
if len(moves) < 9 {
return "Pending"
}
return "Draw"
}
```

View File

@ -0,0 +1,87 @@
# [1380. Lucky Numbers in a Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix/)
## 题目
Given a `m * n` matrix of **distinct** numbers, return all lucky numbers in the matrix in **any** order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1**:
```
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column
```
**Example 2**:
```
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
```
**Example 3**:
```
Input: matrix = [[7,8],[1,2]]
Output: [7]
```
**Constraints**:
- `m == mat.length`
- `n == mat[i].length`
- `1 <= n, m <= 50`
- `1 <= matrix[i][j] <= 10^5`.
- All elements in the matrix are distinct.
## 题目大意
给你一个 m * n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。幸运数是指矩阵中满足同时下列两个条件的元素:
- 在同一行的所有元素中最小
- 在同一列的所有元素中最大
## 解题思路
- 找出矩阵中的幸运数。幸运数的定义:同时满足 2 个条件,在同一行的所有元素中最小并且在同一列的所有元素中最大。
- 简单题。按照题意遍历矩阵,找到同时满足 2 个条件的数输出即可。
## 代码
```go
package leetcode
func luckyNumbers(matrix [][]int) []int {
t, r, res := make([]int, len(matrix[0])), make([]int, len(matrix[0])), []int{}
for _, val := range matrix {
m, k := val[0], 0
for j := 0; j < len(matrix[0]); j++ {
if val[j] < m {
m = val[j]
k = j
}
if t[j] < val[j] {
t[j] = val[j]
}
}
if t[k] == m {
r[k] = m
}
}
for k, v := range r {
if v > 0 && v == t[k] {
res = append(res, v)
}
}
return res
}
```

View File

@ -0,0 +1,98 @@
# [1385. Find the Distance Value Between Two Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays/)
## 题目
Given two integer arrays `arr1` and `arr2`, and the integer `d`, *return the distance value between the two arrays*.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1**:
```
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2
```
**Example 2**:
```
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2
```
**Example 3**:
```
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
```
**Constraints**:
- `1 <= arr1.length, arr2.length <= 500`
- `-10^3 <= arr1[i], arr2[j] <= 10^3`
- `0 <= d <= 100`
## 题目大意
给你两个整数数组 arr1  arr2 和一个整数 d 请你返回两个数组之间的 距离值 。「距离值」 定义为符合此距离要求的元素数目对于元素 arr1[i] 不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d 。
提示:
- 1 <= arr1.length, arr2.length <= 500
- -10^3 <= arr1[i], arr2[j] <= 10^3
- 0 <= d <= 100
## 解题思路
- 计算两个数组之间的距离,距离值的定义:满足对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d 这一条件的元素数目。
- 简单题,按照距离值的定义,双层循环计数即可。
## 代码
```go
package leetcode
func findTheDistanceValue(arr1 []int, arr2 []int, d int) int {
res := 0
for i := range arr1 {
for j := range arr2 {
if abs(arr1[i]-arr2[j]) <= d {
break
}
if j == len(arr2)-1 {
res++
}
}
}
return res
}
func abs(a int) int {
if a < 0 {
return -1 * a
}
return a
}
```

View File

@ -0,0 +1,90 @@
# [1389. Create Target Array in the Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order/)
## 题目
Given two arrays of integers `nums` and `index`. Your task is to create *target* array under the following rules:
- Initially *target* array is empty.
- From left to right read nums[i] and index[i], insert at index `index[i]` the value `nums[i]` in *target* array.
- Repeat the previous step until there are no elements to read in `nums` and `index.`
Return the *target* array.
It is guaranteed that the insertion operations will be valid.
**Example 1**:
```
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
```
**Example 2**:
```
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]
```
**Example 3**:
```
Input: nums = [1], index = [0]
Output: [1]
```
**Constraints**:
- `1 <= nums.length, index.length <= 100`
- `nums.length == index.length`
- `0 <= nums[i] <= 100`
- `0 <= index[i] <= i`
## 题目大意
给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组
- 目标数组 target 最初为空。
- 按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。
- 重复上一步,直到在 nums 和 index 中都没有要读取的元素。
请你返回目标数组。题目保证数字插入位置总是存在。
## 解题思路
- 给定 2 个数组,分别装的是待插入的元素和待插入的位置。最后输出操作完成的数组。
- 简单题,按照题意插入元素即可。
## 代码
```go
package leetcode
func createTargetArray(nums []int, index []int) []int {
result := make([]int, len(nums))
for i, pos := range index {
copy(result[pos+1:i+1], result[pos:i])
result[pos] = nums[i]
}
return result
}
```