1. Add solution 1091、1614、1619、1624、1629、1636、1704

2. ctl strings.TrimSpace question.Title
This commit is contained in:
YDZ
2021-02-14 12:30:19 +08:00
parent af41c91d60
commit 14d0942f5a
57 changed files with 2046 additions and 271 deletions

View File

@ -0,0 +1,54 @@
package leetcode
var dir = [][]int{
{-1, -1},
{-1, 0},
{-1, 1},
{0, 1},
{0, -1},
{1, -1},
{1, 0},
{1, 1},
}
func shortestPathBinaryMatrix(grid [][]int) int {
visited := make([][]bool, 0)
for range make([]int, len(grid)) {
visited = append(visited, make([]bool, len(grid[0])))
}
dis := make([][]int, 0)
for range make([]int, len(grid)) {
dis = append(dis, make([]int, len(grid[0])))
}
if grid[0][0] == 1 {
return -1
}
if len(grid) == 1 && len(grid[0]) == 1 {
return 1
}
queue := []int{0}
visited[0][0], dis[0][0] = true, 1
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
curx, cury := cur/len(grid[0]), cur%len(grid[0])
for d := 0; d < 8; d++ {
nextx := curx + dir[d][0]
nexty := cury + dir[d][1]
if isInBoard(grid, nextx, nexty) && !visited[nextx][nexty] && grid[nextx][nexty] == 0 {
queue = append(queue, nextx*len(grid[0])+nexty)
visited[nextx][nexty] = true
dis[nextx][nexty] = dis[curx][cury] + 1
if nextx == len(grid)-1 && nexty == len(grid[0])-1 {
return dis[nextx][nexty]
}
}
}
}
return -1
}
func isInBoard(board [][]int, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}

View File

@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question1091 struct {
para1091
ans1091
}
// para 是参数
// one 代表第一个参数
type para1091 struct {
grid [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1091 struct {
one int
}
func Test_Problem1091(t *testing.T) {
qs := []question1091{
{
para1091{[][]int{{0, 1}, {1, 0}}},
ans1091{2},
},
{
para1091{[][]int{{0, 0, 0}, {1, 1, 0}, {1, 1, 0}}},
ans1091{4},
},
}
fmt.Printf("------------------------Leetcode Problem 1091------------------------\n")
for _, q := range qs {
_, p := q.ans1091, q.para1091
fmt.Printf("【input】:%v 【output】:%v\n", p, shortestPathBinaryMatrix(p.grid))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,114 @@
# [1091. Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/)
## 题目
In an N by N square grid, each cell is either empty (0) or blocked (1).
A *clear path from top-left to bottom-right* has length `k` if and only if it is composed of cells `C_1, C_2, ..., C_k` such that:
- Adjacent cells `C_i` and `C_{i+1}` are connected 8-directionally (ie., they are different and share an edge or corner)
- `C_1` is at location `(0, 0)` (ie. has value `grid[0][0]`)
- `C_k` is at location `(N-1, N-1)` (ie. has value `grid[N-1][N-1]`)
- If `C_i` is located at `(r, c)`, then `grid[r][c]` is empty (ie. `grid[r][c] == 0`).
Return the length of the shortest such clear path from top-left to bottom-right.  If such a path does not exist, return -1.
**Example 1:**
```
Input: [[0,1],[1,0]]
Output: 2
```
![https://assets.leetcode.com/uploads/2019/08/04/example1_1.png](https://assets.leetcode.com/uploads/2019/08/04/example1_1.png)
![https://assets.leetcode.com/uploads/2019/08/04/example1_2.png](https://assets.leetcode.com/uploads/2019/08/04/example1_2.png)
**Example 2:**
```
Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
```
![https://assets.leetcode.com/uploads/2019/08/04/example2_1.png](https://assets.leetcode.com/uploads/2019/08/04/example2_1.png)
![https://assets.leetcode.com/uploads/2019/08/04/example2_2.png](https://assets.leetcode.com/uploads/2019/08/04/example2_2.png)
**Note:**
1. `1 <= grid.length == grid[0].length <= 100`
2. `grid[r][c]` is `0` or `1`
## 题目大意
在一个 N × N 的方形网格中每个单元格有两种状态0或者阻塞1。一条从左上角到右下角、长度为 k 的畅通路径由满足下述条件的单元格 C_1, C_2, ..., C_k 组成
- 相邻单元格 C_i 和 C_{i+1} 在八个方向之一上连通此时C_i 和 C_{i+1} 不同且共享边或角)
- C_1 位于 (0, 0)值为 grid[0][0]
- C_k 位于 (N-1, N-1)值为 grid[N-1][N-1]
- 如果 C_i 位于 (r, c),则 grid[r][c] 为空grid[r][c] == 0
返回这条从左上角到右下角的最短畅通路径的长度。如果不存在这样的路径,返回 -1 。
## 解题思路
- 这一题是简单的找最短路径。利用 BFS 从左上角逐步扩展到右下角,便可以很容易求解。注意每轮扩展需要考虑 8 个方向。
## 代码
```go
var dir = [][]int{
{-1, -1},
{-1, 0},
{-1, 1},
{0, 1},
{0, -1},
{1, -1},
{1, 0},
{1, 1},
}
func shortestPathBinaryMatrix(grid [][]int) int {
visited := make([][]bool, 0)
for range make([]int, len(grid)) {
visited = append(visited, make([]bool, len(grid[0])))
}
dis := make([][]int, 0)
for range make([]int, len(grid)) {
dis = append(dis, make([]int, len(grid[0])))
}
if grid[0][0] == 1 {
return -1
}
if len(grid) == 1 && len(grid[0]) == 1 {
return 1
}
queue := []int{0}
visited[0][0], dis[0][0] = true, 1
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
curx, cury := cur/len(grid[0]), cur%len(grid[0])
for d := 0; d < 8; d++ {
nextx := curx + dir[d][0]
nexty := cury + dir[d][1]
if isInBoard(grid, nextx, nexty) && !visited[nextx][nexty] && grid[nextx][nexty] == 0 {
queue = append(queue, nextx*len(grid[0])+nexty)
visited[nextx][nexty] = true
dis[nextx][nexty] = dis[curx][cury] + 1
if nextx == len(grid)-1 && nexty == len(grid[0])-1 {
return dis[nextx][nexty]
}
}
}
}
return -1
}
func isInBoard(board [][]int, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}
```

View File

@ -0,0 +1,21 @@
package leetcode
func maxDepth(s string) int {
res, cur := 0, 0
for _, c := range s {
if c == '(' {
cur++
res = max(res, cur)
} else if c == ')' {
cur--
}
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}

View File

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

View File

@ -0,0 +1,102 @@
# [1614. Maximum Nesting Depth of the Parentheses](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/)
## 题目
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following:
- It is an empty string `""`, or a single character not equal to `"("` or `")"`,
- It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or
- It can be written as `(A)`, where `A` is a **VPS**.
We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows:
- `depth("") = 0`
- `depth(C) = 0`, where `C` is a string with a single character not equal to `"("` or `")"`.
- `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s.
- `depth("(" + A + ")") = 1 + depth(A)`, where `A` is a **VPS**.
For example, `""`, `"()()"`, and `"()(()())"` are **VPS**'s (with nesting depths 0, 1, and 2), and `")("` and `"(()"` are not **VPS**'s.
Given a **VPS** represented as string `s`, return *the **nesting depth** of* `s`.
**Example 1:**
```
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.
```
**Example 2:**
```
Input: s = "(1)+((2))+(((3)))"
Output: 3
```
**Example 3:**
```
Input: s = "1+(2*3)/(2-1)"
Output: 1
```
**Example 4:**
```
Input: s = "1"
Output: 0
```
**Constraints:**
- `1 <= s.length <= 100`
- `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
- It is guaranteed that parentheses expression `s` is a **VPS**.
## 题目大意
如果字符串满足以下条件之一,则可以称之为 有效括号字符串valid parentheses string可以简写为 VPS
- 字符串是一个空字符串 "",或者是一个不为 "(" 或 ")" 的单字符。
- 字符串可以写为 ABA 与 B 字符串连接其中 A 和 B 都是 有效括号字符串 。
- 字符串可以写为 (A),其中 A 是一个 有效括号字符串 。
类似地可以定义任何有效括号字符串 S 的 嵌套深度 depth(S)
- depth("") = 0
- depth(C) = 0其中 C 是单个字符的字符串,且该字符不是 "(" 或者 ")"
- depth(A + B) = max(depth(A), depth(B)),其中 A 和 B 都是 有效括号字符串
- depth("(" + A + ")") = 1 + depth(A),其中 A 是一个 有效括号字符串
例如:""、"()()"、"()(()())" 都是 有效括号字符串(嵌套深度分别为 0、1、2而 ")(" 、"(()" 都不是 有效括号字符串 。给你一个 有效括号字符串 s返回该字符串的 s 嵌套深度 。
## 解题思路
- 简单题。求一个括号字符串的嵌套深度。题目给的括号字符串都是有效的,所以不需要考虑非法的情况。扫描一遍括号字符串,遇到 `(` 可以无脑 ++,并动态维护最大值,遇到 `)` 可以无脑 - - 。最后输出最大值即可。
## 代码
```go
package leetcode
func maxDepth(s string) int {
res, cur := 0, 0
for _, c := range s {
if c == '(' {
cur++
res = max(res, cur)
} else if c == ')' {
cur--
}
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```

View File

@ -0,0 +1,12 @@
package leetcode
import "sort"
func trimMean(arr []int) float64 {
sort.Ints(arr)
n, sum := len(arr), 0
for i := n / 20; i < n-(n/20); i++ {
sum += arr[i]
}
return float64(sum) / float64((n - (n / 10)))
}

View File

@ -0,0 +1,62 @@
package leetcode
import (
"fmt"
"testing"
)
type question1619 struct {
para1619
ans1619
}
// para 是参数
// one 代表第一个参数
type para1619 struct {
p []int
}
// ans 是答案
// one 代表第一个答案
type ans1619 struct {
one float64
}
func Test_Problem1619(t *testing.T) {
qs := []question1619{
{
para1619{[]int{1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3}},
ans1619{2.00000},
},
{
para1619{[]int{6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0}},
ans1619{4.00000},
},
{
para1619{[]int{6, 0, 7, 0, 7, 5, 7, 8, 3, 4, 0, 7, 8, 1, 6, 8, 1, 1, 2, 4, 8, 1, 9, 5, 4, 3, 8, 5, 10, 8, 6, 6, 1, 0, 6, 10, 8, 2, 3, 4}},
ans1619{4.77778},
},
{
para1619{[]int{9, 7, 8, 7, 7, 8, 4, 4, 6, 8, 8, 7, 6, 8, 8, 9, 2, 6, 0, 0, 1, 10, 8, 6, 3, 3, 5, 1, 10, 9, 0, 7, 10, 0, 10, 4, 1, 10, 6, 9, 3, 6, 0, 0, 2, 7, 0, 6, 7, 2, 9, 7, 7, 3, 0, 1, 6, 1, 10, 3}},
ans1619{5.27778},
},
{
para1619{[]int{4, 8, 4, 10, 0, 7, 1, 3, 7, 8, 8, 3, 4, 1, 6, 2, 1, 1, 8, 0, 9, 8, 0, 3, 9, 10, 3, 10, 1, 10, 7, 3, 2, 1, 4, 9, 10, 7, 6, 4, 0, 8, 5, 1, 2, 1, 6, 2, 5, 0, 7, 10, 9, 10, 3, 7, 10, 5, 8, 5, 7, 6, 7, 6, 10, 9, 5, 10, 5, 5, 7, 2, 10, 7, 7, 8, 2, 0, 1, 1}},
ans1619{5.29167},
},
}
fmt.Printf("------------------------Leetcode Problem 1619------------------------\n")
for _, q := range qs {
_, p := q.ans1619, q.para1619
fmt.Printf("【input】:%v 【output】:%v \n", p, trimMean(p.p))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,74 @@
# [1619. Mean of Array After Removing Some Elements](https://leetcode.com/problems/mean-of-array-after-removing-some-elements/)
## 题目
Given an integer array `arr`, return *the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements.*
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
```
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
```
**Example 2:**
```
Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
Output: 4.00000
```
**Example 3:**
```
Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
Output: 4.77778
```
**Example 4:**
```
Input: arr = [9,7,8,7,7,8,4,4,6,8,8,7,6,8,8,9,2,6,0,0,1,10,8,6,3,3,5,1,10,9,0,7,10,0,10,4,1,10,6,9,3,6,0,0,2,7,0,6,7,2,9,7,7,3,0,1,6,1,10,3]
Output: 5.27778
```
**Example 5:**
```
Input: arr = [4,8,4,10,0,7,1,3,7,8,8,3,4,1,6,2,1,1,8,0,9,8,0,3,9,10,3,10,1,10,7,3,2,1,4,9,10,7,6,4,0,8,5,1,2,1,6,2,5,0,7,10,9,10,3,7,10,5,8,5,7,6,7,6,10,9,5,10,5,5,7,2,10,7,7,8,2,0,1,1]
Output: 5.29167
```
**Constraints:**
- `20 <= arr.length <= 1000`
- `arr.length` **is a multiple** of `20`.
- `0 <= arr[i] <= 10^5`
## 题目大意
给你一个整数数组 `arr` ,请你删除最小 `5%` 的数字和最大 `5%` 的数字后,剩余数字的平均值。与 **标准答案** 误差在 `10-5` 的结果都被视为正确结果。
## 解题思路
- 简单题。先将数组排序,然后累加中间 90% 的元素,最后计算平均值。
## 代码
```go
package leetcode
import "sort"
func trimMean(arr []int) float64 {
sort.Ints(arr)
n, sum := len(arr), 0
for i := n / 20; i < n-(n/20); i++ {
sum += arr[i]
}
return float64(sum) / float64((n - (n / 10)))
}
```

View File

@ -0,0 +1,16 @@
package leetcode
import "strings"
func maxLengthBetweenEqualCharacters(s string) int {
res := -1
for k, v := range s {
tmp := strings.LastIndex(s, string(v))
if tmp > 0 {
if res < tmp-k-1 {
res = tmp - k - 1
}
}
}
return res
}

View File

@ -0,0 +1,57 @@
package leetcode
import (
"fmt"
"testing"
)
type question1624 struct {
para1624
ans1624
}
// para 是参数
// one 代表第一个参数
type para1624 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1624 struct {
one int
}
func Test_Problem1624(t *testing.T) {
qs := []question1624{
{
para1624{"aa"},
ans1624{0},
},
{
para1624{"abca"},
ans1624{2},
},
{
para1624{"cbzxy"},
ans1624{-1},
},
{
para1624{"cabbac"},
ans1624{4},
},
}
fmt.Printf("------------------------Leetcode Problem 1624------------------------\n")
for _, q := range qs {
_, p := q.ans1624, q.para1624
fmt.Printf("【input】:%v 【output】:%v \n", p, maxLengthBetweenEqualCharacters(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,73 @@
# [1624. Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters/)
## 题目
Given a string `s`, return *the length of the longest substring between two equal characters, excluding the two characters.* If there is no such substring return `-1`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
```
Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty substring between the two 'a's.
```
**Example 2:**
```
Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".
```
**Example 3:**
```
Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.
```
**Example 4:**
```
Input: s = "cabbac"
Output: 4
Explanation: The optimal substring here is "abba". Other non-optimal substrings include "bb" and "".
```
**Constraints:**
- `1 <= s.length <= 300`
- `s` contains only lowercase English letters.
## 题目大意
给你一个字符串 s请你返回 两个相同字符之间的最长子字符串的长度 ,计算长度时不含这两个字符。如果不存在这样的子字符串,返回 -1 。子字符串 是字符串中的一个连续字符序列。
## 解题思路
- 简单题。取每个字符,扫描一次字符串,如果在字符串中还能找到相同的字符,则返回最末尾的那个字符,计算这两个字符之间的距离。取最末尾的字符是为了让两个相同的字符距离最长。扫描字符串过程中动态维护最长长度。如果字符串中不存在 2 个相同的字符,则返回 -1 。
## 代码
```go
package leetcode
import "strings"
func maxLengthBetweenEqualCharacters(s string) int {
res := -1
for k, v := range s {
tmp := strings.LastIndex(s, string(v))
if tmp > 0 {
if res < tmp-k-1 {
res = tmp - k - 1
}
}
}
return res
}
```

View File

@ -0,0 +1,15 @@
package leetcode
func slowestKey(releaseTimes []int, keysPressed string) byte {
longestDuration, key := releaseTimes[0], keysPressed[0]
for i := 1; i < len(releaseTimes); i++ {
duration := releaseTimes[i] - releaseTimes[i-1]
if duration > longestDuration {
longestDuration = duration
key = keysPressed[i]
} else if duration == longestDuration && keysPressed[i] > key {
key = keysPressed[i]
}
}
return key
}

View File

@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question1629 struct {
para1629
ans1629
}
// para 是参数
// one 代表第一个参数
type para1629 struct {
releaseTimes []int
keysPressed string
}
// ans 是答案
// one 代表第一个答案
type ans1629 struct {
one byte
}
func Test_Problem1629(t *testing.T) {
qs := []question1629{
{
para1629{[]int{9, 29, 49, 50}, "cbcd"},
ans1629{'c'},
},
{
para1629{[]int{12, 23, 36, 46, 62}, "spuda"},
ans1629{'a'},
},
}
fmt.Printf("------------------------Leetcode Problem 1629------------------------\n")
for _, q := range qs {
_, p := q.ans1629, q.para1629
fmt.Printf("【input】:%v 【output】:%c \n", p, slowestKey(p.releaseTimes, p.keysPressed))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,83 @@
# [1629. Slowest Key](https://leetcode.com/problems/slowest-key/)
## 题目
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released.
The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`.
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**.
*Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.*
**Example 1:**
```
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
```
**Example 2:**
```
Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
```
**Constraints:**
- `releaseTimes.length == n`
- `keysPressed.length == n`
- `2 <= n <= 1000`
- `1 <= releaseTimes[i] <= 109`
- `releaseTimes[i] < releaseTimes[i+1]`
- `keysPressed` contains only lowercase English letters.
## 题目大意
LeetCode 设计了一款新式键盘,正在测试其可用性。测试人员将会点击一系列键(总计 n 个),每次一个。
给你一个长度为 n 的字符串 keysPressed ,其中 keysPressed[i] 表示测试序列中第 i 个被按下的键。releaseTimes 是一个升序排列的列表,其中 releaseTimes[i] 表示松开第 i 个键的时间。字符串和数组的 下标都从 0 开始 。第 0 个键在时间为 0 时被按下,接下来每个键都 恰好 在前一个键松开时被按下。测试人员想要找出按键 持续时间最长 的键。第 i 次按键的持续时间为 releaseTimes[i] - releaseTimes[i - 1] ,第 0 次按键的持续时间为 releaseTimes[0] 。
注意,测试期间,同一个键可以在不同时刻被多次按下,而每次的持续时间都可能不同。请返回按键 持续时间最长 的键,如果有多个这样的键,则返回 按字母顺序排列最大 的那个键。
## 解题思路
- 题干很长,不过还是简单题。循环扫描一遍数组,计算出每个按键的持续时间。动态更新按键最长时间的键。如果持续时间最长的有多个键,需要返回字母序最大的那一个键。
## 代码
```go
package leetcode
func slowestKey(releaseTimes []int, keysPressed string) byte {
longestDuration, key := releaseTimes[0], keysPressed[0]
for i := 1; i < len(releaseTimes); i++ {
duration := releaseTimes[i] - releaseTimes[i-1]
if duration > longestDuration {
longestDuration = duration
key = keysPressed[i]
} else if duration == longestDuration && keysPressed[i] > key {
key = keysPressed[i]
}
}
return key
}
```

View File

@ -0,0 +1,17 @@
package leetcode
import "sort"
func frequencySort(nums []int) []int {
freq := map[int]int{}
for _, v := range nums {
freq[v]++
}
sort.Slice(nums, func(i, j int) bool {
if freq[nums[i]] == freq[nums[j]] {
return nums[j] < nums[i]
}
return freq[nums[i]] < freq[nums[j]]
})
return nums
}

View File

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

View File

@ -0,0 +1,66 @@
# [1636. Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency/)
## 题目
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the *sorted array*.
**Example 1:**
```
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
```
**Example 2:**
```
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
```
**Example 3:**
```
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
```
**Constraints:**
- `1 <= nums.length <= 100`
- `100 <= nums[i] <= 100`
## 题目大意
给你一个整数数组 `nums` ,请你将数组按照每个值的频率 **升序** 排序。如果有多个值的频率相同,请你按照数值本身将它们 **降序** 排序。请你返回排序后的数组。
## 解题思路
- 简单题。先统计每个值的频率,然后按照频率从小到大排序,相同频率的按照值的大小,从大到小排序。
## 代码
```go
package leetcode
import "sort"
func frequencySort(nums []int) []int {
freq := map[int]int{}
for _, v := range nums {
freq[v]++
}
sort.Slice(nums, func(i, j int) bool {
if freq[nums[i]] == freq[nums[j]] {
return nums[j] < nums[i]
}
return freq[nums[i]] < freq[nums[j]]
})
return nums
}
```

View File

@ -5,48 +5,48 @@ import (
"testing"
)
type question1690 struct {
para1690
ans1690
type question1696 struct {
para1696
ans1696
}
// para 是参数
// one 代表第一个参数
type para1690 struct {
type para1696 struct {
nums []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1690 struct {
type ans1696 struct {
one int
}
func Test_Problem1690(t *testing.T) {
func Test_Problem1696(t *testing.T) {
qs := []question1690{
// {
// para1690{[]int{1, -1, -2, 4, -7, 3}, 2},
// ans1690{7},
// },
// {
// para1690{[]int{10, -5, -2, 4, 0, 3}, 3},
// ans1690{17},
// },
qs := []question1696{
{
para1690{[]int{1, -5, -20, 4, -1, 3, -6, -3}, 2},
ans1690{0},
para1696{[]int{1, -1, -2, 4, -7, 3}, 2},
ans1696{7},
},
{
para1696{[]int{10, -5, -2, 4, 0, 3}, 3},
ans1696{17},
},
{
para1696{[]int{1, -5, -20, 4, -1, 3, -6, -3}, 2},
ans1696{0},
},
}
fmt.Printf("------------------------Leetcode Problem 1690------------------------\n")
fmt.Printf("------------------------Leetcode Problem 1696------------------------\n")
for _, q := range qs {
_, p := q.ans1690, q.para1690
_, p := q.ans1696, q.para1696
fmt.Printf("【input】:%v 【output】:%v\n", p, maxResult(p.nums, p.k))
}
fmt.Printf("\n\n\n")

View File

@ -0,0 +1,16 @@
package leetcode
func halvesAreAlike(s string) bool {
return numVowels(s[len(s)/2:]) == numVowels(s[:len(s)/2])
}
func numVowels(x string) int {
res := 0
for _, c := range x {
switch c {
case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
res++
}
}
return res
}

View File

@ -0,0 +1,57 @@
package leetcode
import (
"fmt"
"testing"
)
type question1704 struct {
para1704
ans1704
}
// para 是参数
// one 代表第一个参数
type para1704 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1704 struct {
one bool
}
func Test_Problem1704(t *testing.T) {
qs := []question1704{
{
para1704{"book"},
ans1704{true},
},
{
para1704{"textbook"},
ans1704{false},
},
{
para1704{"MerryChristmas"},
ans1704{false},
},
{
para1704{"AbCdEfGh"},
ans1704{true},
},
}
fmt.Printf("------------------------Leetcode Problem 1704------------------------\n")
for _, q := range qs {
_, p := q.ans1704, q.para1704
fmt.Printf("【input】:%v 【output】:%v\n", p, halvesAreAlike(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,75 @@
# [1704. Determine if String Halves Are Alike](https://leetcode.com/problems/determine-if-string-halves-are-alike/)
## 题目
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` *if* `a` *and* `b` *are **alike***. Otherwise, return `false`.
**Example 1:**
```
Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
```
**Example 2:**
```
Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
```
**Example 3:**
```
Input: s = "MerryChristmas"
Output: false
```
**Example 4:**
```
Input: s = "AbCdEfGh"
Output: true
```
**Constraints:**
- `2 <= s.length <= 1000`
- `s.length` is even.
- `s` consists of **uppercase and lowercase** letters.
## 题目大意
给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b 。两个字符串 相似 的前提是它们都含有相同数目的元音('a''e''i''o''u''A''E''I''O''U'。注意s 可能同时含有大写和小写字母。如果 a 和 b 相似,返回 true ;否则,返回 false 。
## 解题思路
- 简单题。依题意,分别统计前半段元音字母的个数和后半段元音字母的个数,个数相同则输出 true不同就输出 false。
## 代码
```go
package leetcode
func halvesAreAlike(s string) bool {
return numVowels(s[len(s)/2:]) == numVowels(s[:len(s)/2])
}
func numVowels(x string) int {
res := 0
for _, c := range x {
switch c {
case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
res++
}
}
return res
}
```