This commit is contained in:
novahe
2021-11-28 21:57:43 +08:00
156 changed files with 9087 additions and 3603 deletions

3855
README.md

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,23 @@
package leetcode
import "sort"
func longestCommonPrefix(strs []string) string {
sort.Slice(strs, func(i, j int) bool {
return len(strs[i]) <= len(strs[j])
})
minLen := len(strs[0])
if minLen == 0 {
return ""
}
var commonPrefix []byte
for i := 0; i < minLen; i++ {
for j := 1; j < len(strs); j++ {
if strs[j][i] != strs[0][i] {
return string(commonPrefix)
}
}
commonPrefix = append(commonPrefix, strs[0][i])
}
return string(commonPrefix)
}

View File

@ -0,0 +1,45 @@
package leetcode
import (
"fmt"
"testing"
)
type question14 struct {
para14
ans14
}
// para 是参数
type para14 struct {
strs []string
}
// ans 是答案
type ans14 struct {
ans string
}
func Test_Problem14(t *testing.T) {
qs := []question14{
{
para14{[]string{"flower", "flow", "flight"}},
ans14{"fl"},
},
{
para14{[]string{"dog", "racecar", "car"}},
ans14{""},
},
}
fmt.Printf("------------------------Leetcode Problem 14------------------------\n")
for _, q := range qs {
_, p := q.ans14, q.para14
fmt.Printf("【input】:%v 【output】:%v\n", p.strs, longestCommonPrefix(p.strs))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,64 @@
# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)
## 题目
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
**Example 1**:
Input: strs = ["flower","flow","flight"]
Output: "fl"
**Example 2**:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
**Constraints:**
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
## 题目大意
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
## 解题思路
- 对 strs 按照字符串长度进行升序排序,求出 strs 中长度最小字符串的长度 minLen
- 逐个比较长度最小字符串与其它字符串中的字符,如果不相等就返回 commonPrefix,否则就把该字符加入 commonPrefix
## 代码
```go
package leetcode
import "sort"
func longestCommonPrefix(strs []string) string {
sort.Slice(strs, func(i, j int) bool {
return len(strs[i]) <= len(strs[j])
})
minLen := len(strs[0])
if minLen == 0 {
return ""
}
var commonPrefix []byte
for i := 0; i < minLen; i++ {
for j := 1; j < len(strs); j++ {
if strs[j][i] != strs[0][i] {
return string(commonPrefix)
}
}
commonPrefix = append(commonPrefix, strs[0][i])
}
return string(commonPrefix)
}
```

View File

@ -1,5 +1,6 @@
package leetcode
// 解法一
func nextPermutation(nums []int) {
i, j := 0, 0
for i = len(nums) - 2; i >= 0; i-- {
@ -29,3 +30,43 @@ func reverse(nums *[]int, i, j int) {
func swap(nums *[]int, i, j int) {
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
}
// 解法二
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
func nextPermutation1(nums []int) {
var n = len(nums)
var pIdx = checkPermutationPossibility(nums)
if pIdx == -1 {
reverse(&nums, 0, n-1)
return
}
var rp = len(nums) - 1
// start from right most to leftward,find the first number which is larger than PIVOT
for rp > 0 {
if nums[rp] > nums[pIdx] {
swap(&nums, pIdx, rp)
break
} else {
rp--
}
}
// Finally, Reverse all elements which are right from pivot
reverse(&nums, pIdx+1, n-1)
}
// checkPermutationPossibility returns 1st occurrence Index where
// value is in decreasing order(from right to left)
// returns -1 if not found(it's already in its last permutation)
func checkPermutationPossibility(nums []int) (idx int) {
// search right to left for 1st number(from right) that is not in increasing order
var rp = len(nums) - 1
for rp > 0 {
if nums[rp-1] < nums[rp] {
idx = rp - 1
return idx
}
rp--
}
return -1
}

View File

@ -1,5 +1,6 @@
package leetcode
// 解法一
func rotate(matrix [][]int) {
length := len(matrix)
// rotate by diagonal 对角线变换
@ -15,3 +16,46 @@ func rotate(matrix [][]int) {
}
}
}
// 解法二
func rotate1(matrix [][]int) {
n := len(matrix)
if n == 1 {
return
}
/* rotate clock-wise = 1. transpose matrix => 2. reverse(matrix[i])
1 2 3 4 1 5 9 13 13 9 5 1
5 6 7 8 => 2 6 10 14 => 14 10 6 2
9 10 11 12 3 7 11 15 15 11 7 3
13 14 15 16 4 8 12 16 16 12 8 4
*/
for i := 0; i < n; i++ {
// transpose, i=rows, j=columns
// j = i+1, coz diagonal elements didn't change in a square matrix
for j := i + 1; j < n; j++ {
swap(matrix, i, j)
}
// reverse each row of the image
matrix[i] = reverse(matrix[i])
}
}
// swap changes original slice's i,j position
func swap(nums [][]int, i, j int) {
nums[i][j], nums[j][i] = nums[j][i], nums[i][j]
}
// reverses a row of image, matrix[i]
func reverse(nums []int) []int {
var lp, rp = 0, len(nums) - 1
for lp < rp {
nums[lp], nums[rp] = nums[rp], nums[lp]
lp++
rp--
}
return nums
}

View File

@ -0,0 +1,16 @@
package leetcode
func lengthOfLastWord(s string) int {
last := len(s) - 1
for last >= 0 && s[last] == ' ' {
last--
}
if last < 0 {
return 0
}
first := last
for first >= 0 && s[first] != ' ' {
first--
}
return last - first
}

View File

@ -0,0 +1,50 @@
package leetcode
import (
"fmt"
"testing"
)
type question58 struct {
para58
ans58
}
// para 是参数
type para58 struct {
s string
}
// ans 是答案
type ans58 struct {
ans int
}
func Test_Problem58(t *testing.T) {
qs := []question58{
{
para58{"Hello World"},
ans58{5},
},
{
para58{" fly me to the moon "},
ans58{4},
},
{
para58{"luffy is still joyboy"},
ans58{6},
},
}
fmt.Printf("------------------------Leetcode Problem 58------------------------\n")
for _, q := range qs {
_, p := q.ans58, q.para58
fmt.Printf("【input】:%v 【output】:%v\n", p, lengthOfLastWord(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,70 @@
# [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/)
## 题目
Given a string `s` consisting of some words separated by some number of spaces, return *the length of the **last** word in the string.*
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
```
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
```
**Example 2:**
```
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
```
**Example 3:**
```
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
```
**Constraints:**
- `1 <= s.length <= 104`
- `s` consists of only English letters and spaces `' '`.
- There will be at least one word in `s`.
## 题目大意
给你一个字符串 `s`,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。**单词** 是指仅由字母组成、不包含任何空格字符的最大子字符串。
## 解题思路
- 先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度。
## 代码
```go
package leetcode
func lengthOfLastWord(s string) int {
last := len(s) - 1
for last >= 0 && s[last] == ' ' {
last--
}
if last < 0 {
return 0
}
first := last
for first >= 0 && s[first] != ' ' {
first--
}
return last - first
}
```

View File

@ -26,4 +26,4 @@ Your algorithm should have a linear runtime complexity. Could you implement it w
## 解题思路
- 题目要求不能使用辅助空间,并且时间复杂度只能是线性的。
- 题目为什么要强调有一个数字出现一次其他的出现两次我们想到了异或运算的性质任何一个数字异或它自己都等于0。也就是说如果我们从头到尾依次异或数组中的每一个数字那么最终的结果刚好是那个只出现次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。
- 题目为什么要强调有一个数字出现一次其他的出现两次我们想到了异或运算的性质任何一个数字异或它自己都等于0。也就是说如果我们从头到尾依次异或数组中的每一个数字那么最终的结果刚好是那个只出现次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。

View File

@ -0,0 +1,31 @@
package leetcode
import "strconv"
func getHint(secret string, guess string) string {
cntA, cntB := 0, 0
mpS := make(map[byte]int)
var strG []byte
n := len(secret)
var ans string
for i := 0; i < n; i++ {
if secret[i] == guess[i] {
cntA++
} else {
mpS[secret[i]] += 1
strG = append(strG, guess[i])
}
}
for _, v := range strG {
if _, ok := mpS[v]; ok {
if mpS[v] > 1 {
mpS[v] -= 1
} else {
delete(mpS, v)
}
cntB++
}
}
ans += strconv.Itoa(cntA) + "A" + strconv.Itoa(cntB) + "B"
return ans
}

View File

@ -0,0 +1,56 @@
package leetcode
import (
"fmt"
"testing"
)
type question299 struct {
para299
ans299
}
// para 是参数
type para299 struct {
secret string
guess string
}
// ans 是答案
type ans299 struct {
ans string
}
func Test_Problem299(t *testing.T) {
qs := []question299{
{
para299{"1807", "7810"},
ans299{"1A3B"},
},
{
para299{"1123", "0111"},
ans299{"1A1B"},
},
{
para299{"1", "0"},
ans299{"0A0B"},
},
{
para299{"1", "1"},
ans299{"1A0B"},
},
}
fmt.Printf("------------------------Leetcode Problem 299------------------------\n")
for _, q := range qs {
_, p := q.ans299, q.para299
fmt.Printf("【input】:%v 【output】:%v\n", p, getHint(p.secret, p.guess))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,114 @@
# [299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)
## 题目
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
**Example 1:**
```
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"
```
**Example 2:**
```
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
```
**Example 3:**
```
Input: secret = "1", guess = "0"
Output: "0A0B"
```
**Example 4:**
```
Input: secret = "1", guess = "1"
Output: "1A0B"
```
**Constraints:**
- 1 <= secret.length, guess.length <= 1000
- secret.length == guess.length
- secret and guess consist of digits only.
## 题目大意
你在和朋友一起玩 猜数字Bulls and Cows游戏该游戏规则如下
写出一个秘密数字,并请朋友猜这个数字是多少。朋友每猜测一次,你就会给他一个包含下述信息的提示:
猜测数字中有多少位属于数字和确切位置都猜对了(称为 "Bulls", 公牛),
有多少位属于数字猜对了但是位置不对(称为 "Cows", 奶牛)。也就是说,这次猜测中有多少位非公牛数字可以通过重新排列转换成公牛数字。
给你一个秘密数字secret 和朋友猜测的数字guess ,请你返回对朋友这次猜测的提示。
提示的格式为 "xAyB" x 是公牛个数, y 是奶牛个数A 表示公牛B表示奶牛。
请注意秘密数字和朋友猜测的数字都可能含有重复数字。
## 解题思路
- 计算下标一致并且对应下标的元素一致的个数,即 x
- secret 和 guess 分别去除 x 个公牛的元素,剩下 secret 和 guess 求共同的元素个数就是 y
- 把 x y 转换成字符串,分别与 "A" 和 "B" 进行拼接返回结果
## 代码
```go
package leetcode
import "strconv"
func getHint(secret string, guess string) string {
cntA, cntB := 0, 0
mpS := make(map[byte]int)
var strG []byte
n := len(secret)
var ans string
for i := 0; i < n; i++ {
if secret[i] == guess[i] {
cntA++
} else {
mpS[secret[i]] += 1
strG = append(strG, guess[i])
}
}
for _, v := range strG {
if _, ok := mpS[v]; ok {
if mpS[v] > 1 {
mpS[v] -= 1
} else {
delete(mpS, v)
}
cntB++
}
}
ans += strconv.Itoa(cntA) + "A" + strconv.Itoa(cntB) + "B"
return ans
}
```

View File

@ -0,0 +1,69 @@
package leetcode
var (
res []string
mp map[string]int
n int
length int
maxScore int
str string
)
func removeInvalidParentheses(s string) []string {
lmoves, rmoves, lcnt, rcnt := 0, 0, 0, 0
for _, v := range s {
if v == '(' {
lmoves++
lcnt++
} else if v == ')' {
if lmoves != 0 {
lmoves--
} else {
rmoves++
}
rcnt++
}
}
n = len(s)
length = n - lmoves - rmoves
res = []string{}
mp = make(map[string]int)
maxScore = min(lcnt, rcnt)
str = s
backtrace(0, "", lmoves, rmoves, 0)
return res
}
func backtrace(i int, cur string, lmoves int, rmoves int, score int) {
if lmoves < 0 || rmoves < 0 || score < 0 || score > maxScore {
return
}
if lmoves == 0 && rmoves == 0 {
if len(cur) == length {
if _, ok := mp[cur]; !ok {
res = append(res, cur)
mp[cur] = 1
}
return
}
}
if i == n {
return
}
if str[i] == '(' {
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
backtrace(i+1, cur, lmoves-1, rmoves, score)
} else if str[i] == ')' {
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
backtrace(i+1, cur, lmoves, rmoves-1, score)
} else {
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}

View File

@ -0,0 +1,50 @@
package leetcode
import (
"fmt"
"testing"
)
type question301 struct {
para301
ans301
}
// s 是参数
type para301 struct {
s string
}
// ans 是答案
type ans301 struct {
ans []string
}
func Test_Problem301(t *testing.T) {
qs := []question301{
{
para301{"()())()"},
ans301{[]string{"(())()", "()()()"}},
},
{
para301{"(a)())()"},
ans301{[]string{"(a())()", "(a)()()"}},
},
{
para301{")("},
ans301{[]string{""}},
},
}
fmt.Printf("------------------------Leetcode Problem 301------------------------\n")
for _, q := range qs {
_, p := q.ans301, q.para301
fmt.Printf("【input】:%v 【output】:%v\n", p, removeInvalidParentheses(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,131 @@
# [301. Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)
## 题目
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
**Example 1:**
Input: s = "()())()"
Output: ["(())()","()()()"]
**Example 2:**
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
**Example 3:**
Input: s = ")("
Output: [""]
**Constraints:**
- 1 <= s.length <= 25
- s consists of lowercase English letters and parentheses '(' and ')'.
- There will be at most 20 parentheses in s.
## 题目大意
给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。
返回所有可能的结果。答案可以按 任意顺序 返回。
说明:
- 1 <= s.length <= 25
- s 由小写英文字母以及括号 '(' 和 ')' 组成
- s 中至多含 20 个括号
## 解题思路
回溯和剪枝
- 计算最大得分数maxScore合法字符串的长度length左括号和右括号的移除次数lmoves,rmoves
- 加一个左括号的得分加1加一个右括号的得分减1
- 对于一个合法的字符串左括号等于右括号得分最终为0
- 搜索过程中出现以下任何一种情况都直接返回
- 得分值为负数
- 得分大于最大得分数
- 得分小于0
- lmoves小于0
- rmoves小于0
## 代码
```go
package leetcode
var (
res []string
mp map[string]int
n int
length int
maxScore int
str string
)
func removeInvalidParentheses(s string) []string {
lmoves, rmoves, lcnt, rcnt := 0, 0, 0, 0
for _, v := range s {
if v == '(' {
lmoves++
lcnt++
} else if v == ')' {
if lmoves != 0 {
lmoves--
} else {
rmoves++
}
rcnt++
}
}
n = len(s)
length = n - lmoves - rmoves
res = []string{}
mp = make(map[string]int)
maxScore = min(lcnt, rcnt)
str = s
backtrace(0, "", lmoves, rmoves, 0)
return res
}
func backtrace(i int, cur string, lmoves int, rmoves int, score int) {
if lmoves < 0 || rmoves < 0 || score < 0 || score > maxScore {
return
}
if lmoves == 0 && rmoves == 0 {
if len(cur) == length {
if _, ok := mp[cur]; !ok {
res = append(res, cur)
mp[cur] = 1
}
return
}
}
if i == n {
return
}
if str[i] == '(' {
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
backtrace(i+1, cur, lmoves-1, rmoves, score)
} else if str[i] == ')' {
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
backtrace(i+1, cur, lmoves, rmoves-1, score)
} else {
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
```

View File

@ -0,0 +1,7 @@
package leetcode
import "math"
func bulbSwitch(n int) int {
return int(math.Sqrt(float64(n)))
}

View File

@ -0,0 +1,50 @@
package leetcode
import (
"fmt"
"testing"
)
type question319 struct {
para319
ans319
}
// para 是参数
type para319 struct {
n int
}
// ans 是答案
type ans319 struct {
ans int
}
func Test_Problem319(t *testing.T) {
qs := []question319{
{
para319{3},
ans319{1},
},
{
para319{0},
ans319{0},
},
{
para319{1},
ans319{1},
},
}
fmt.Printf("------------------------Leetcode Problem 319------------------------\n")
for _, q := range qs {
_, p := q.ans319, q.para319
fmt.Printf("【input】:%v 【output】:%v\n", p, bulbSwitch(p.n))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,58 @@
# [319. Bulb Switcher](https://leetcode.com/problems/bulb-switcher/)
## 题目
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
Return the number of bulbs that are on after n rounds.
**Example 1:**
Input: n = 3
Output: 1
Explanation: At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.
**Example 2:**
Input: n = 0
Output: 0
**Example 3:**
Input: n = 1
Output: 1
## 题目大意
初始时有 n 个灯泡处于关闭状态。第一轮,你将会打开所有灯泡。接下来的第二轮,你将会每两个灯泡关闭一个。
第三轮,你每三个灯泡就切换一个灯泡的开关(即,打开变关闭,关闭变打开)。第 i 轮,你每 i 个灯泡就切换一个灯泡的开关。直到第 n 轮,你只需要切换最后一个灯泡的开关。
找出并返回 n 轮后有多少个亮着的灯泡。
## 解题思路
- 计算 1 到 n 中有奇数个约数的个数
- 1 到 n 中的某个数 x 有奇数个约数,也即 x 是完全平方数
- 计算 1 到 n 中完全平方数的个数 sqrt(n)
## 代码
```go
package leetcode
import "math"
func bulbSwitch(n int) int {
return int(math.Sqrt(float64(n)))
}
```

View File

@ -31,4 +31,4 @@ Note:
## 解题思路
这道题思路也是一样的,分别把奇数和偶数都放在 2 个链表中,最后首尾拼接就是答案。
这道题思路也是一样的,分别把奇数节点和偶数节点都放在 2 个链表中,最后首尾拼接就是答案。

View File

@ -0,0 +1,49 @@
package leetcode
import "sort"
type SummaryRanges struct {
nums []int
mp map[int]int
}
func Constructor() SummaryRanges {
return SummaryRanges{
nums: []int{},
mp: map[int]int{},
}
}
func (this *SummaryRanges) AddNum(val int) {
if _, ok := this.mp[val]; !ok {
this.mp[val] = 1
this.nums = append(this.nums, val)
}
sort.Ints(this.nums)
}
func (this *SummaryRanges) GetIntervals() [][]int {
n := len(this.nums)
var ans [][]int
if n == 0 {
return ans
}
if n == 1 {
ans = append(ans, []int{this.nums[0], this.nums[0]})
return ans
}
start, end := this.nums[0], this.nums[0]
ans = append(ans, []int{start, end})
index := 0
for i := 1; i < n; i++ {
if this.nums[i] == end+1 {
end = this.nums[i]
ans[index][1] = end
} else {
start, end = this.nums[i], this.nums[i]
ans = append(ans, []int{start, end})
index++
}
}
return ans
}

View File

@ -0,0 +1,63 @@
package leetcode
import (
"fmt"
"testing"
)
type question352 struct {
para352
ans352
}
// para 是参数
type para352 struct {
para string
num int
}
// ans 是答案
type ans352 struct {
ans [][]int
}
func Test_Problem352(t *testing.T) {
qs := []question352{
{
para352{"addNum", 1},
ans352{[][]int{{1, 1}}},
},
{
para352{"addNum", 3},
ans352{[][]int{{1, 1}, {3, 3}}},
},
{
para352{"addNum", 7},
ans352{[][]int{{1, 1}, {3, 3}, {7, 7}}},
},
{
para352{"addNum", 2},
ans352{[][]int{{1, 3}, {7, 7}}},
},
{
para352{"addNum", 6},
ans352{[][]int{{1, 3}, {6, 7}}},
},
}
fmt.Printf("------------------------Leetcode Problem 352------------------------\n")
obj := Constructor()
for _, q := range qs {
_, p := q.ans352, q.para352
obj.AddNum(p.num)
fmt.Printf("【input】:%v 【output】:%v\n", p, obj.GetIntervals())
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,108 @@
# [352. Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/)
## 题目
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.
Implement the SummaryRanges class:
- SummaryRanges() Initializes the object with an empty stream.
- void addNum(int val) Adds the integer val to the stream.
- int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi].
**Example 1:**
Input
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
Output
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
Explanation
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // return [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
**Constraints**
- 0 <= val <= 10000
- At most 3 * 10000 calls will be made to addNum and getIntervals.
## 题目大意
给你一个由非负整数a1, a2, ..., an 组成的数据流输入,请你将到目前为止看到的数字总结为不相交的区间列表。
实现 SummaryRanges 类:
- SummaryRanges() 使用一个空数据流初始化对象。
- void addNum(int val) 向数据流中加入整数 val 。
- int[][] getIntervals() 以不相交区间[starti, endi] 的列表形式返回对数据流中整数的总结
## 解题思路
- 使用字典过滤掉重复的数字
- 把过滤后的数字放到nums中,并进行排序
- 使用nums构建不重复的区间
## 代码
```go
package leetcode
import "sort"
type SummaryRanges struct {
nums []int
mp map[int]int
}
func Constructor() SummaryRanges {
return SummaryRanges{
nums: []int{},
mp : map[int]int{},
}
}
func (this *SummaryRanges) AddNum(val int) {
if _, ok := this.mp[val]; !ok {
this.mp[val] = 1
this.nums = append(this.nums, val)
}
sort.Ints(this.nums)
}
func (this *SummaryRanges) GetIntervals() [][]int {
n := len(this.nums)
var ans [][]int
if n == 0 {
return ans
}
if n == 1 {
ans = append(ans, []int{this.nums[0], this.nums[0]})
return ans
}
start, end := this.nums[0], this.nums[0]
ans = append(ans, []int{start, end})
index := 0
for i := 1; i < n; i++ {
if this.nums[i] == end + 1 {
end = this.nums[i]
ans[index][1] = end
} else {
start, end = this.nums[i], this.nums[i]
ans = append(ans, []int{start, end})
index++
}
}
return ans
}
```

View File

@ -0,0 +1,28 @@
package leetcode
import "math/rand"
type Solution struct {
nums []int
}
func Constructor(nums []int) Solution {
return Solution{
nums: nums,
}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.nums
}
/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
arr := make([]int, len(this.nums))
copy(arr, this.nums)
rand.Shuffle(len(arr), func(i, j int) {
arr[i], arr[j] = arr[j], arr[i]
})
return arr
}

View File

@ -0,0 +1,50 @@
package leetcode
import (
"fmt"
"testing"
)
type question384 struct {
para384
ans384
}
// para 是参数
type para384 struct {
ops []string
value [][]int
}
// ans 是答案
type ans384 struct {
ans [][]int
}
func Test_Problem384(t *testing.T) {
qs := []question384{
{
para384{ops: []string{"Solution", "shuffle", "reset", "shuffle"}, value: [][]int{{1, 2, 3}, {}, {}, {}}},
ans384{[][]int{nil, {3, 1, 2}, {1, 2, 3}, {1, 3, 2}}},
},
}
fmt.Printf("------------------------Leetcode Problem 384------------------------\n")
for _, q := range qs {
sol := Constructor(nil)
_, p := q.ans384, q.para384
for _, op := range p.ops {
if op == "Solution" {
sol = Constructor(q.value[0])
} else if op == "reset" {
fmt.Printf("【input】:%v 【output】:%v\n", op, sol.Reset())
} else {
fmt.Printf("【input】:%v 【output】:%v\n", op, sol.Shuffle())
}
}
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,82 @@
# [384.Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)
## 题目
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution class:
- Solution(int[] nums) Initializes the object with the integer array nums.
- int[] reset() Resets the array to its original configuration and returns it.
- int[] shuffle() Returns a random shuffling of the array.
**Example 1**:
Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
// Any permutation of [1,2,3] must be equally likely to be returned.
// Example: return [3, 1, 2]
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
**Constraints:**
- 1 <= nums.length <= 200
- -1000000 <= nums[i] <= 1000000
- All the elements of nums are unique.
- At most 5 * 10000 calls in total will be made to reset and shuffle.
## 题目大意
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
实现 Solution class:
- Solution(int[] nums) 使用整数数组 nums 初始化对象
- int[] reset() 重设数组到它的初始状态并返回
- int[] shuffle() 返回数组随机打乱后的结果
## 解题思路
- 使用 rand.Shuffle 进行数组随机打乱
## 代码
```go
package leetcode
import "math/rand"
type Solution struct {
nums []int
}
func Constructor(nums []int) Solution {
return Solution{
nums: nums,
}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.nums
}
/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
arr := make([]int, len(this.nums))
copy(arr, this.nums)
rand.Shuffle(len(arr), func(i, j int) {
arr[i], arr[j] = arr[j], arr[i]
})
return arr
}
```

View File

@ -0,0 +1,53 @@
package leetcode
type point struct {
x int
y int
}
func isRectangleCover(rectangles [][]int) bool {
minX, minY, maxA, maxB := rectangles[0][0], rectangles[0][1], rectangles[0][2], rectangles[0][3]
area := 0
cnt := make(map[point]int)
for _, v := range rectangles {
x, y, a, b := v[0], v[1], v[2], v[3]
area += (a - x) * (b - y)
minX = min(minX, x)
minY = min(minY, y)
maxA = max(maxA, a)
maxB = max(maxB, b)
cnt[point{x, y}]++
cnt[point{a, b}]++
cnt[point{x, b}]++
cnt[point{a, y}]++
}
if area != (maxA-minX)*(maxB-minY) ||
cnt[point{minX, minY}] != 1 || cnt[point{maxA, maxB}] != 1 ||
cnt[point{minX, maxB}] != 1 || cnt[point{maxA, minY}] != 1 {
return false
}
delete(cnt, point{minX, minY})
delete(cnt, point{maxA, maxB})
delete(cnt, point{minX, maxB})
delete(cnt, point{maxA, minY})
for _, v := range cnt {
if v != 2 && v != 4 {
return false
}
}
return true
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}

View File

@ -0,0 +1,55 @@
package leetcode
import (
"fmt"
"testing"
)
type question391 struct {
para391
ans391
}
// para 是参数
type para391 struct {
rectangles [][]int
}
// ans 是答案
type ans391 struct {
ans bool
}
func Test_Problem391(t *testing.T) {
qs := []question391{
{
para391{[][]int{{1, 1, 3, 3}, {3, 1, 4, 2}, {3, 2, 4, 4}, {1, 3, 2, 4}, {2, 3, 3, 4}}},
ans391{true},
},
{
para391{[][]int{{1, 1, 2, 3}, {1, 3, 2, 4}, {3, 1, 4, 2}, {3, 2, 4, 4}}},
ans391{false},
},
{
para391{[][]int{{1, 1, 3, 3}, {3, 1, 4, 2}, {1, 3, 2, 4}, {3, 2, 4, 4}}},
ans391{false},
},
{
para391{[][]int{{1, 1, 3, 3}, {3, 1, 4, 2}, {1, 3, 2, 4}, {2, 2, 4, 4}}},
ans391{false},
},
}
fmt.Printf("------------------------Leetcode Problem 391------------------------\n")
for _, q := range qs {
_, p := q.ans391, q.para391
fmt.Printf("【input】:%v 【output】:%v\n", p, isRectangleCover(p.rectangles))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,114 @@
# [391. Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/)
## 题目
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
Return true if all the rectangles together form an exact cover of a rectangular region.
**Example1:**
![https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg)
Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]
Output: true
Explanation: All 5 rectangles together form an exact cover of a rectangular region.
**Example2:**
![https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg)
Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]
Output: false
Explanation: Because there is a gap between the two rectangular regions.
**Example3:**
![https://assets.leetcode.com/uploads/2021/03/27/perfectrec3-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perfectrec3-plane.jpg)
Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]
Output: false
Explanation: Because there is a gap in the top center.
**Example4:**
![https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg)
Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]
Output: false
Explanation: Because two of the rectangles overlap with each other.
**Constraints:**
- 1 <= rectangles.length <= 2 * 10000
- rectangles[i].length == 4
- -100000 <= xi, yi, ai, bi <= 100000
## 题目大意
给你一个数组 rectangles ,其中 rectangles[i] = [xi, yi, ai, bi] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (xi, yi) ,右上顶点是 (ai, bi) 。
如果所有矩形一起精确覆盖了某个矩形区域,则返回 true ;否则,返回 false 。
## 解题思路
- 矩形区域的面积等于所有矩形的面积之和并且满足矩形区域四角的顶点只能出现一次,且其余顶点的出现次数只能是两次或四次则返回 true,否则返回 false
## 代码
```go
package leetcode
type point struct {
x int
y int
}
func isRectangleCover(rectangles [][]int) bool {
minX, minY, maxA, maxB := rectangles[0][0], rectangles[0][1], rectangles[0][2], rectangles[0][3]
area := 0
cnt := make(map[point]int)
for _, v := range rectangles {
x, y, a, b := v[0], v[1], v[2], v[3]
area += (a - x) * (b - y)
minX = min(minX, x)
minY = min(minY, y)
maxA = max(maxA, a)
maxB = max(maxB, b)
cnt[point{x, y}]++
cnt[point{a, b}]++
cnt[point{x, b}]++
cnt[point{a, y}]++
}
if area != (maxA - minX) * (maxB - minY) ||
cnt[point{minX, minY}] != 1 || cnt[point{maxA, maxB}] != 1 ||
cnt[point{minX, maxB}] != 1 || cnt[point{maxA, minY}] != 1 {
return false
}
delete(cnt, point{minX, minY})
delete(cnt, point{maxA, maxB})
delete(cnt, point{minX, maxB})
delete(cnt, point{maxA, minY})
for _, v := range cnt {
if v != 2 && v != 4 {
return false
}
}
return true
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```

View File

@ -0,0 +1,18 @@
package leetcode
func countSegments(s string) int {
segments := false
cnt := 0
for _, v := range s {
if v == ' ' && segments {
segments = false
cnt += 1
} else if v != ' ' {
segments = true
}
}
if segments {
cnt++
}
return cnt
}

View File

@ -0,0 +1,55 @@
package leetcode
import (
"fmt"
"testing"
)
type question434 struct {
para434
ans434
}
// s 是参数
type para434 struct {
s string
}
// ans 是答案
type ans434 struct {
ans int
}
func Test_Problem434(t *testing.T) {
qs := []question434{
{
para434{"Hello, my name is John"},
ans434{5},
},
{
para434{"Hello"},
ans434{1},
},
{
para434{"love live! mu'sic forever"},
ans434{4},
},
{
para434{""},
ans434{0},
},
}
fmt.Printf("------------------------Leetcode Problem 434------------------------\n")
for _, q := range qs {
_, p := q.ans434, q.para434
fmt.Printf("【input】:%v 【output】:%v\n", p, countSegments(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,70 @@
# [434. Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/)
## 题目
You are given a string s, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
**Example 1:**
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
**Example 2:**
Input: s = "Hello"
Output: 1
**Example 3:**
Input: s = "love live! mu'sic forever"
Output: 4
**Example 4:**
Input: s = ""
Output: 0
**Constraints**
- 0 <= s.length <= 300
- s consists of lower-case and upper-case English letters, digits or one of the following characters "!@#$%^&*()_+-=',.:".
- The only space character in s is ' '.
## 题目大意
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
## 解题思路
- 以空格为分割计算元素个数
## 代码
```go
package leetcode
func countSegments(s string) int {
segments := false
cnt := 0
for _, v := range s {
if v == ' ' && segments {
segments = false
cnt += 1
} else if v != ' ' {
segments = true
}
}
if segments {
cnt++
}
return cnt
}
```

View File

@ -0,0 +1,8 @@
package leetcode
import "math"
func poorPigs(buckets int, minutesToDie int, minutesToTest int) int {
base := minutesToTest/minutesToDie + 1
return int(math.Ceil(math.Log10(float64(buckets)) / math.Log10(float64(base))))
}

View File

@ -0,0 +1,52 @@
package leetcode
import (
"fmt"
"testing"
)
type question458 struct {
para458
ans458
}
// para 是参数
type para458 struct {
buckets int
minutesToDie int
minutesToTest int
}
// ans 是答案
type ans458 struct {
ans int
}
func Test_Problem458(t *testing.T) {
qs := []question458{
{
para458{1000, 15, 60},
ans458{5},
},
{
para458{4, 15, 15},
ans458{2},
},
{
para458{4, 15, 30},
ans458{2},
},
}
fmt.Printf("------------------------Leetcode Problem 458------------------------\n")
for _, q := range qs {
_, p := q.ans458, q.para458
fmt.Printf("【input】:%v 【output】:%v\n", p, poorPigs(p.buckets, p.minutesToDie, p.minutesToTest))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,77 @@
# [458. Poor Pigs](https://leetcode.com/problems/poor-pigs/)
## 题目
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
- Choose some live pigs to feed.
- For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
- Wait for minutesToDie minutes. You may not feed any other pigs during this time.
- After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
- Repeat this process until you run out of time.
Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
**Example 1**:
Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60
Output: 5
**Example 2**:
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
Output: 2
**Example 3**:
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
Output: 2
**Constraints:**
- 1 <= buckets <= 1000
- 1 <= minutesToDie <= minutesToTest <= 100
## 题目大意
有 buckets 桶液体,其中 正好 有一桶含有毒药其余装的都是水。它们从外观看起来都一样。为了弄清楚哪只水桶含有毒药你可以喂一些猪喝通过观察猪是否会死进行判断。不幸的是你只有 minutesToTest 分钟时间来确定哪桶液体是有毒的。
喂猪的规则如下:
- 选择若干活猪进行喂养
- 可以允许小猪同时饮用任意数量的桶中的水,并且该过程不需要时间。
- 小猪喝完水后,必须有 minutesToDie 分钟的冷却时间。在这段时间里,你只能观察,而不允许继续喂猪。
- 过了 minutesToDie 分钟后,所有喝到毒药的猪都会死去,其他所有猪都会活下来。
- 重复这一过程,直到时间用完。
给你桶的数目 buckets minutesToDie 和 minutesToTest ,返回在规定时间内判断哪个桶有毒所需的 最小 猪数。
## 解题思路
使用数学方法,以 minutesToDie=15, minutesToTest=60, 1 只小猪为例,可以测试 5 只桶
- 0-15 小猪吃第一个桶中的液体,如果死去,则第一个桶有毒,否则继续测试
- 15-30 小猪吃第二个桶中的液体,如果死去,则第二个桶有毒,否则继续测试
- 30-45 小猪吃第三个桶中的液体,如果死去,则第三个桶有毒,否则继续测试
- 45-60 小猪吃第四个桶中的液体,如果死去,则第四个桶有毒
- 如果最后小猪没有死去,则第五个桶有毒
所以一只小猪在 minutesToDie 和 minutesToTest 时间一定的情况下可以最多判断 base = minutesToTest / minutesToDie + 1 个桶
假设小猪的数量是 num,那么 pow(base, num) >= buckets,根据对数运算规则,两边分别取对数得到: num >= Log10(buckets) / Log10(base)
## 代码
```go
package leetcode
import "math"
func poorPigs(buckets int, minutesToDie int, minutesToTest int) int {
base := minutesToTest/minutesToDie + 1
return int(math.Ceil(math.Log10(float64(buckets)) / math.Log10(float64(base))))
}
```

View File

@ -0,0 +1,50 @@
package leetcode
func findMinStep(board string, hand string) int {
q := [][]string{{board, hand}}
mp := make(map[string]bool)
minStep := 0
for len(q) > 0 {
length := len(q)
minStep++
for length > 0 {
length--
cur := q[0]
q = q[1:]
curB, curH := cur[0], cur[1]
for i := 0; i < len(curB); i++ {
for j := 0; j < len(curH); j++ {
curB2 := del3(curB[0:i] + string(curH[j]) + curB[i:])
curH2 := curH[0:j] + curH[j+1:]
if len(curB2) == 0 {
return minStep
}
if _, ok := mp[curB2+curH2]; ok {
continue
}
mp[curB2+curH2] = true
q = append(q, []string{curB2, curH2})
}
}
}
}
return -1
}
func del3(str string) string {
cnt := 1
for i := 1; i < len(str); i++ {
if str[i] == str[i-1] {
cnt++
} else {
if cnt >= 3 {
return del3(str[0:i-cnt] + str[i:])
}
cnt = 1
}
}
if cnt >= 3 {
return str[0 : len(str)-cnt]
}
return str
}

View File

@ -0,0 +1,56 @@
package leetcode
import (
"fmt"
"testing"
)
type question488 struct {
para488
ans488
}
// para 是参数
type para488 struct {
board string
hand string
}
// ans 是答案
type ans488 struct {
ans int
}
func Test_Problem488(t *testing.T) {
qs := []question488{
{
para488{"WRRBBW", "RB"},
ans488{-1},
},
{
para488{"WWRRBBWW", "WRBRW"},
ans488{2},
},
{
para488{"G", "GGGGG"},
ans488{2},
},
{
para488{"RBYYBBRRB", "YRBGB"},
ans488{3},
},
}
fmt.Printf("------------------------Leetcode Problem 488------------------------\n")
for _, q := range qs {
_, p := q.ans488, q.para488
fmt.Printf("【input】:%v 【output】:%v\n", p, findMinStep(p.board, p.hand))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,141 @@
# [488. Zuma Game](https://leetcode.com/problems/zuma-game/)
## 题目
You are playing a variation of the game Zuma.
In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.
Your goal is to clear all of the balls from the board. On each turn:
Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.
If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.
If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.
If there are no more balls on the board, then you win the game.
Repeat this process until you either win or do not have any more balls in your hand.
Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.
**Example 1**:
```
Input: board = "WRRBBW", hand = "RB"
Output: -1
Explanation: It is impossible to clear all the balls. The best you can do is:
- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.
- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.
There are still balls remaining on the board, and you are out of balls to insert.
```
**Example 2**:
```
Input: board = "WWRRBBWW", hand = "WRBRW"
Output: 2
Explanation: To make the board empty:
- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.
- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty.
2 balls from your hand were needed to clear the board.
```
**Example 3**:
```
Input: board = "G", hand = "GGGGG"
Output: 2
Explanation: To make the board empty:
- Insert 'G' so the board becomes GG.
- Insert 'G' so the board becomes GGG. GGG -> empty.
2 balls from your hand were needed to clear the board.
```
**Example 4**:
```
Input: board = "RBYYBBRRB", hand = "YRBGB"
Output: 3
Explanation: To make the board empty:
- Insert 'Y' so the board becomes RBYYYBBRRB. RBYYYBBRRB -> RBBBRRB -> RRRB -> B.
- Insert 'B' so the board becomes BB.
- Insert 'B' so the board becomes BBB. BBB -> empty.
3 balls from your hand were needed to clear the board.
```
**Constraints**:
- 1 <= board.length <= 16
- 1 <= hand.length <= 5
- board and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'.
- The initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.
## 题目大意
你正在参与祖玛游戏的一个变种。
在这个祖玛游戏变体中,桌面上有 一排 彩球,每个球的颜色可能是:红色 'R'、黄色 'Y'、蓝色 'B'、绿色 'G' 或白色 'W' 。你的手中也有一些彩球。
你的目标是 清空 桌面上所有的球。每一回合:
从你手上的彩球中选出 任意一颗 ,然后将其插入桌面上那一排球中:两球之间或这一排球的任一端。
接着,如果有出现 三个或者三个以上 且 颜色相同 的球相连的话,就把它们移除掉。
如果这种移除操作同样导致出现三个或者三个以上且颜色相同的球相连,则可以继续移除这些球,直到不再满足移除条件。
如果桌面上所有球都被移除,则认为你赢得本场游戏。
重复这个过程,直到你赢了游戏或者手中没有更多的球。
给你一个字符串 board ,表示桌面上最开始的那排球。另给你一个字符串 hand ,表示手里的彩球。请你按上述操作步骤移除掉桌上所有球,计算并返回所需的 最少 球数。如果不能移除桌上所有的球,返回 -1 。
## 解题思路
- 使用广度优先搜索和剪枝
## 代码
```go
package leetcode
func findMinStep(board string, hand string) int {
q := [][]string{{board, hand}}
mp := make(map[string]bool)
minStep := 0
for len(q) > 0 {
length := len(q)
minStep++
for length > 0 {
length--
cur := q[0]
q = q[1:]
curB, curH := cur[0], cur[1]
for i := 0; i < len(curB); i++ {
for j := 0; j < len(curH); j++ {
curB2 := del3(curB[0:i] + string(curH[j]) + curB[i:])
curH2 := curH[0:j] + curH[j+1:]
if len(curB2) == 0 {
return minStep
}
if _, ok := mp[curB2+curH2]; ok {
continue
}
mp[curB2+curH2] = true
q = append(q, []string{curB2, curH2})
}
}
}
}
return -1
}
func del3(str string) string {
cnt := 1
for i := 1; i < len(str); i++ {
if str[i] == str[i-1] {
cnt++
} else {
if cnt >= 3 {
return del3(str[0:i-cnt] + str[i:])
}
cnt = 1
}
}
if cnt >= 3 {
return str[0 : len(str)-cnt]
}
return str
}
```

View File

@ -0,0 +1,16 @@
package leetcode
import "math"
func constructRectangle(area int) []int {
ans := make([]int, 2)
W := int(math.Sqrt(float64(area)))
for W >= 1 {
if area%W == 0 {
ans[0], ans[1] = area/W, W
break
}
W -= 1
}
return ans
}

View File

@ -0,0 +1,50 @@
package leetcode
import (
"fmt"
"testing"
)
type question492 struct {
para492
ans492
}
// area 是参数
type para492 struct {
area int
}
// ans 是答案
type ans492 struct {
ans []int
}
func Test_Problem492(t *testing.T) {
qs := []question492{
{
para492{4},
ans492{[]int{2, 2}},
},
{
para492{37},
ans492{[]int{37, 1}},
},
{
para492{122122},
ans492{[]int{427, 286}},
},
}
fmt.Printf("------------------------Leetcode Problem 492------------------------\n")
for _, q := range qs {
_, p := q.ans492, q.para492
fmt.Printf("【input】:%v 【output】:%v\n", p, constructRectangle(p.area))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,72 @@
# [492. Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/)
## 题目
A web developer needs to know how to design a web page's size.
So, given a specific rectangular web pages area, your job by now is to design a rectangular web page,
whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area.
The width W should not be larger than the length L, which means L >= W.
The difference between length L and width W should be as small as possible.
Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.
**Example 1:**
Input: area = 4
Output: [2,2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
**Example 2:**
Input: area = 37
Output: [37,1]
**Example 3:**
Input: area = 122122
Output: [427,286]
**Constraints**
- 1 <= area <= 10000000
## 题目大意
作为一位 web 开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:
1. 你设计的矩形页面必须等于给定的目标面积。
2. 宽度 W 不应大于长度 L换言之要求 L >= W 。
3. 长度 L 和宽度 W 之间的差距应当尽可能小。
你需要按顺序输出你设计的页面的长度 L 和宽度 W。
## 解题思路
- 令 W 等于根号 area
- 在 W 大于等于 1 的情况下,判断 area%W 是否等于 0,如果不相等 W 就减 1 继续循环,如果相等就返回 [area/W, W]
## 代码
```go
package leetcode
import "math"
func constructRectangle(area int) []int {
ans := make([]int, 2)
W := int(math.Sqrt(float64(area)))
for W >= 1 {
if area%W == 0 {
ans[0], ans[1] = area/W, W
break
}
W -= 1
}
return ans
}
``

View File

@ -6,7 +6,7 @@ func findTargetSumWays(nums []int, S int) int {
for _, n := range nums {
total += n
}
if S > total || (S+total)%2 == 1 {
if S > total || (S+total)%2 == 1 || S+total < 0 {
return 0
}
target := (S + total) / 2

View File

@ -52,7 +52,7 @@ There are 5 ways to assign symbols to make the sum of nums be target 3.
等号两边都加上 `sum(N) + sum(P)`,于是可以得到结果 `2 * sum(P) = target + sum(nums)`,那么这道题就转换成了,能否在数组中找到这样一个集合,和等于 `(target + sum(nums)) / 2`。那么这题就转化为了第 416 题了。`dp[i]` 中存储的是能使和为 `i` 的方法个数。
- 如果和不是偶数,即不能被 2 整除,那说明找不到满足题目要求的解了,直接输出 0 。
- 如果和不是偶数,即不能被 2 整除,或者和是负数,那说明找不到满足题目要求的解了,直接输出 0 。
## 代码
@ -63,7 +63,7 @@ func findTargetSumWays(nums []int, S int) int {
for _, n := range nums {
total += n
}
if S > total || (S+total)%2 == 1 {
if S > total || (S+total)%2 == 1 || S+total < 0 {
return 0
}
target := (S + total) / 2

View File

@ -0,0 +1,16 @@
package leetcode
func findPoisonedDuration(timeSeries []int, duration int) int {
var ans int
for i := 1; i < len(timeSeries); i++ {
t := timeSeries[i-1]
end := t + duration - 1
if end < timeSeries[i] {
ans += duration
} else {
ans += timeSeries[i] - t
}
}
ans += duration
return ans
}

View File

@ -0,0 +1,46 @@
package leetcode
import (
"fmt"
"testing"
)
type question495 struct {
para495
ans495
}
// para 是参数
type para495 struct {
timeSeries []int
duration int
}
// ans 是答案
type ans495 struct {
ans int
}
func Test_Problem495(t *testing.T) {
qs := []question495{
{
para495{[]int{1, 4}, 2},
ans495{4},
},
{
para495{[]int{1, 2}, 2},
ans495{3},
},
}
fmt.Printf("------------------------Leetcode Problem 495------------------------\n")
for _, q := range qs {
_, p := q.ans495, q.para495
fmt.Printf("【input】:%v 【output】:%v\n", p, findPoisonedDuration(p.timeSeries, p.duration))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,85 @@
# [495. Teemo Attacking](https://leetcode.com/problems/teemo-attacking/)
## 题目
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds.
More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1].
If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.
You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.
Return the total number of seconds that Ashe is poisoned.
**Example 1**:
```
Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
```
**Example 2**:
```
Input: timeSeries = [1,2], duration = 2
Output: 3
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
```
**Constraints**:
- 1 <= timeSeries.length <= 10000
- 0 <= timeSeries[i], duration <= 10000000
- timeSeries is sorted in non-decreasing order.
## 题目大意
在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄。他的攻击可以让敌方英雄艾希(编者注:寒冰射手)进入中毒状态。
当提莫攻击艾希艾希的中毒状态正好持续duration 秒。
正式地讲提莫在t发起发起攻击意味着艾希在时间区间 [t, t + duration - 1](含 t 和 t + duration - 1处于中毒状态。
如果提莫在中毒影响结束前再次攻击中毒状态计时器将会重置在新的攻击之后中毒影响将会在duration秒后结束。
给你一个非递减的整数数组timeSeries其中timeSeries[i]表示提莫在timeSeries[i]秒时对艾希发起攻击以及一个表示中毒持续时间的整数duration 。
返回艾希处于中毒状态的总秒数。
## 解题思路
- i 从 1 开始计数,令 t 等于 timeSeries[i - 1]
- 比较 end(t + duration - 1) 和 timeSeries[i] 的大小,
- 如果 end 小于 timeSeries[i],ans+=duration
- 否则 ans += timeSeries[i] - t
- ans += duration 并返回 ans
## 代码
```go
package leetcode
func findPoisonedDuration(timeSeries []int, duration int) int {
var ans int
for i := 1; i < len(timeSeries); i++ {
t := timeSeries[i-1]
end := t + duration - 1
if end < timeSeries[i] {
ans += duration
} else {
ans += timeSeries[i] - t
}
}
ans += duration
return ans
}
```

View File

@ -37,3 +37,10 @@ The total number of elements of the given matrix will not exceed 10,000.
- 给出一个二维数组,要求按照如图的方式遍历整个数组。
- 这一题用模拟的方式就可以解出来。需要注意的是边界条件:比如二维数组为空,二维数组退化为一行或者一列,退化为一个元素。具体例子见测试用例。
- 解题关键是在判断下一个位置将矩阵想像成一个X,Y坐标轴。那么可分为以下几种情况
1、斜角向右上遍历时
当右上角在坐标轴内, 正常计算 即, x+1(X轴向右移动) y-1(Y轴向上移动)
当右上角在坐标轴外,那么当前位置只能在 第一行X坐标轴 ,或者 最后一列Y坐标轴 即判断该两种情况下<E586B5>应该X坐标往右或者 Y坐标往上
2、同理 斜角向下遍历时
当左下角在坐标轴内,正常计算 即, x-1(X轴向右移动) y+1(Y轴向下移动)
当左下角在坐标轴外,那么当前位置只能在 第一列Y坐标轴或者 最后一行X坐标轴 即判断该两种情况下<E586B5>应该X坐标往左或者 Y坐标往下

View File

@ -0,0 +1,13 @@
package leetcode
import "strings"
func detectCapitalUse(word string) bool {
wLower := strings.ToLower(word)
wUpper := strings.ToUpper(word)
wCaptial := strings.ToUpper(string(word[0])) + strings.ToLower(string(word[1:]))
if wCaptial == word || wLower == word || wUpper == word {
return true
}
return false
}

View File

@ -0,0 +1,45 @@
package leetcode
import (
"fmt"
"testing"
)
type question520 struct {
para520
ans520
}
// para 是参数
type para520 struct {
word string
}
// ans 是答案
type ans520 struct {
ans bool
}
func Test_Problem520(t *testing.T) {
qs := []question520{
{
para520{"USA"},
ans520{true},
},
{
para520{"FlaG"},
ans520{false},
},
}
fmt.Printf("------------------------Leetcode Problem 520------------------------\n")
for _, q := range qs {
_, p := q.ans520, q.para520
fmt.Printf("【input】:%v 【output】:%v\n", p, detectCapitalUse(p.word))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,68 @@
# [520. Detect Capital](https://leetcode.com/problems/detect-capital/)
## 题目
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Given a string word, return true if the usage of capitals in it is right.
**Example 1:**
```
Input: word = "USA"
Output: true
```
**Example 2:**
```
Input: word = "FlaG"
Output: false
```
**Constraints:**
- 1 <= word.length <= 100
- word consists of lowercase and uppercase English letters.
## 题目大意
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如 "USA" 。
单词中所有字母都不是大写,比如 "leetcode" 。
如果单词不只含有一个字母,只有首字母大写,比如"Google" 。
给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false 。
## 解题思路
- 把 word 分别转换为全部小写 wLower全部大写 wUpper首字母大写的字符串 wCaptial
- 判断 word 是否等于 wLower, wUpper, wCaptial 中的一个,如果是返回 true否则返回 false
## 代码
```go
package leetcode
import "strings"
func detectCapitalUse(word string) bool {
wLower := strings.ToLower(word)
wUpper := strings.ToUpper(word)
wCaptial := strings.ToUpper(string(word[0])) + strings.ToLower(string(word[1:]))
if wCaptial == word || wLower == word || wUpper == word {
return true
}
return false
}
```

View File

@ -0,0 +1,22 @@
package leetcode
func checkRecord(s string) bool {
numsA, maxL, numsL := 0, 0, 0
for _, v := range s {
if v == 'L' {
numsL++
} else {
if numsL > maxL {
maxL = numsL
}
numsL = 0
if v == 'A' {
numsA++
}
}
}
if numsL > maxL {
maxL = numsL
}
return numsA < 2 && maxL < 3
}

View File

@ -0,0 +1,45 @@
package leetcode
import (
"fmt"
"testing"
)
type question551 struct {
para551
ans551
}
// para 是参数
type para551 struct {
s string
}
// ans 是答案
type ans551 struct {
ans bool
}
func Test_Problem551(t *testing.T) {
qs := []question551{
{
para551{"PPALLP"},
ans551{true},
},
{
para551{"PPALLL"},
ans551{false},
},
}
fmt.Printf("------------------------Leetcode Problem 551------------------------\n")
for _, q := range qs {
_, p := q.ans551, q.para551
fmt.Printf("【input】:%v 【output】:%v \n", p, checkRecord(p.s))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,86 @@
# [551. Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/)
## 题目
You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
- `'A'`: Absent.
- `'L'`: Late.
- `'P'`: Present.
The student is eligible for an attendance award if they meet **both** of the following criteria:
- The student was absent (`'A'`) for **strictly** fewer than 2 days **total**.
- The student was **never** late (`'L'`) for 3 or more **consecutive** days.
Return `true` *if the student is eligible for an attendance award, or* `false` *otherwise*.
**Example 1:**
```
Input: s = "PPALLP"
Output: true
Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.
```
**Example 2:**
```
Input: s = "PPALLL"
Output: false
Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.
```
**Constraints:**
- `1 <= s.length <= 1000`
- `s[i]` is either `'A'`, `'L'`, or `'P'`.
## 题目大意
给你一个字符串 s 表示一个学生的出勤记录,其中的每个字符用来标记当天的出勤情况(缺勤、迟到、到场)。记录中只含下面三种字符:
- 'A'Absent缺勤
- 'L'Late迟到
- 'P'Present到场
如果学生能够 同时 满足下面两个条件,则可以获得出勤奖励:
- 按 总出勤 计,学生缺勤('A')严格 少于两天。
- 学生 不会 存在 连续 3 天或 连续 3 天以上的迟到('L')记录。
如果学生可以获得出勤奖励,返回 true ;否则,返回 false 。
## 解题思路
- 遍历字符串 s 求出 'A' 的总数量和连续 'L' 的最大数量。
- 比较 'A' 的数量是否小于 2 并且 'L' 的连续最大数量是否小于 3。
## 代码
```go
package leetcode
func checkRecord(s string) bool {
numsA, maxL, numsL := 0, 0, 0
for _, v := range s {
if v == 'L' {
numsL++
} else {
if numsL > maxL {
maxL = numsL
}
numsL = 0
if v == 'A' {
numsA++
}
}
}
if numsL > maxL {
maxL = numsL
}
return numsA < 2 && maxL < 3
}
```

View File

@ -0,0 +1,32 @@
package leetcode
type Node struct {
Val int
Children []*Node
}
func maxDepth(root *Node) int {
if root == nil {
return 0
}
return 1 + bfs(root)
}
func bfs(root *Node) int {
var q []*Node
var depth int
q = append(q, root.Children...)
for len(q) != 0 {
depth++
length := len(q)
for length != 0 {
ele := q[0]
q = q[1:]
length--
if ele != nil && len(ele.Children) != 0 {
q = append(q, ele.Children...)
}
}
}
return depth
}

View File

@ -0,0 +1,60 @@
package leetcode
import (
"fmt"
"testing"
)
type question559 struct {
para559
ans559
}
// para 是参数
type para559 struct {
root *Node
}
// ans 是答案
type ans559 struct {
ans int
}
func Test_Problem559(t *testing.T) {
qs := []question559{
{
para559{&Node{
Val: 1,
Children: []*Node{
{Val: 3, Children: []*Node{{Val: 5, Children: nil}, {Val: 6, Children: nil}}},
{Val: 2, Children: nil},
{Val: 4, Children: nil},
},
}},
ans559{3},
},
{
para559{&Node{
Val: 1,
Children: []*Node{
{Val: 2, Children: nil},
{Val: 3, Children: []*Node{{Val: 6, Children: nil}, {Val: 7, Children: []*Node{{Val: 11, Children: []*Node{{Val: 14, Children: nil}}}}}}},
{Val: 4, Children: []*Node{{Val: 8, Children: []*Node{{Val: 12, Children: nil}}}}},
{Val: 5, Children: []*Node{{Val: 9, Children: []*Node{{Val: 13, Children: nil}}}, {Val: 10, Children: nil}}},
},
}},
ans559{5},
},
}
fmt.Printf("------------------------Leetcode Problem 559------------------------\n")
for _, q := range qs {
_, p := q.ans559, q.para559
fmt.Printf("【input】:%v 【output】:%v\n", p, maxDepth(p.root))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,78 @@
# [559. Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/)
## 题目
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
**Example 1**:
![https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png](https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png)
Input: root = [1,null,3,2,4,null,5,6]
Output: 3
**Example 2**:
![https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png](https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png)
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 5
**Constraints:**
- The total number of nodes is in the range [0, 10000].
- The depth of the n-ary tree is less than or equal to 1000.
## 题目大意
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
## 解题思路
- 使用广度优先遍历
## 代码
```go
package leetcode
type Node struct {
Val int
Children []*Node
}
func maxDepth(root *Node) int {
if root == nil {
return 0
}
return 1 + bfs(root)
}
func bfs(root *Node) int {
var q []*Node
var depth int
q = append(q, root.Children...)
for len(q) != 0 {
depth++
length := len(q)
for length != 0 {
ele := q[0]
q = q[1:]
length--
if ele != nil && len(ele.Children) != 0 {
q = append(q, ele.Children...)
}
}
}
return depth
}
```

View File

@ -0,0 +1,30 @@
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
if root == nil {
return nil
}
if root.Val == val {
return root
} else if root.Val < val {
return searchBST(root.Right, val)
} else {
return searchBST(root.Left, val)
}
}

View File

@ -0,0 +1,51 @@
package leetcode
import (
"fmt"
"testing"
)
type question700 struct {
para700
ans700
}
// para 是参数
type para700 struct {
root *TreeNode
val int
}
// ans 是答案
type ans700 struct {
ans *TreeNode
}
func Test_Problem700(t *testing.T) {
qs := []question700{
{
para700{&TreeNode{Val: 4,
Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}},
Right: &TreeNode{Val: 7, Left: nil, Right: nil}},
2},
ans700{&TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}}},
},
{
para700{&TreeNode{Val: 4,
Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}},
Right: &TreeNode{Val: 7, Left: nil, Right: nil}},
5},
ans700{nil},
},
}
fmt.Printf("------------------------Leetcode Problem 700------------------------\n")
for _, q := range qs {
_, p := q.ans700, q.para700
fmt.Printf("【input】:%v 【output】:%v\n", p, searchBST(p.root, p.val))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,73 @@
# [700. Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/)
## 题目
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
**Example 1**:
![https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg](https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg)
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
**Example 2**:
![https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg](https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg)
Input: root = [4,2,7,1,3], val = 5
Output: []
**Constraints:**
- The number of nodes in the tree is in the range [1, 5000].
- 1 <= Node.val <= 10000000
- root is a binary search tree.
- 1 <= val <= 10000000
## 题目大意
给定二叉搜索树BST的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
## 解题思路
- 根据二叉搜索树的性质(根节点的值大于左子树所有节点的值,小于右子树所有节点的值),进行递归求解
## 代码
```go
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
if root == nil {
return nil
}
if root.Val == val {
return root
} else if root.Val < val {
return searchBST(root.Right, val)
} else {
return searchBST(root.Left, val)
}
}
```

View File

@ -0,0 +1,30 @@
package leetcode
func buddyStrings(s string, goal string) bool {
if len(s) != len(goal) || len(s) <= 1 {
return false
}
mp := make(map[byte]int)
if s == goal {
for i := 0; i < len(s); i++ {
if _, ok := mp[s[i]]; ok {
return true
}
mp[s[i]]++
}
return false
}
first, second := -1, -1
for i := 0; i < len(s); i++ {
if s[i] != goal[i] {
if first == -1 {
first = i
} else if second == -1 {
second = i
} else {
return false
}
}
}
return second != -1 && s[first] == goal[second] && s[second] == goal[first]
}

View File

@ -0,0 +1,56 @@
package leetcode
import (
"fmt"
"testing"
)
type question859 struct {
para859
ans859
}
// para 是参数
type para859 struct {
s string
goal string
}
// ans 是答案
type ans859 struct {
ans bool
}
func Test_Problem859(t *testing.T) {
qs := []question859{
{
para859{"ab", "ba"},
ans859{true},
},
{
para859{"ab", "ab"},
ans859{false},
},
{
para859{"aa", "aa"},
ans859{true},
},
{
para859{"aaaaaaabc", "aaaaaaacb"},
ans859{true},
},
}
fmt.Printf("------------------------Leetcode Problem 859------------------------\n")
for _, q := range qs {
_, p := q.ans859, q.para859
fmt.Printf("【input】:%v 【output】:%v\n", p, buddyStrings(p.s, p.goal))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,87 @@
# [859. Buddy Strings](https://leetcode.com/problems/buddy-strings/)
## 题目
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
**Example 1**:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
**Example 2**:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
**Example 3**:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
**Example 4**:
Input: s = "aaaaaaabc", goal = "aaaaaaacb"
Output: true
**Constraints:**
- 1 <= s.length, goal.length <= 2 * 10000
- s and goal consist of lowercase letters.
## 题目大意
给你两个字符串 s 和 goal ,只要我们可以通过交换 s 中的两个字母得到与 goal 相等的结果,就返回 true否则返回 false 。
交换字母的定义是:取两个下标 i 和 j (下标从 0 开始)且满足 i != j ,接着交换 s[i] 和 s[j] 处的字符。
例如,在 "abcd" 中交换下标 0 和下标 2 的元素可以生成 "cbad" 。
## 解题思路
分为两种情况进行比较:
- s 等于 goal, s 中有重复元素就返回 true,否则返回 false
- s 不等于 goal, s 中有两个下标不同的字符与 goal 中对应下标的字符分别相等
## 代码
```go
package leetcode
func buddyStrings(s string, goal string) bool {
if len(s) != len(goal) || len(s) <= 1 {
return false
}
mp := make(map[byte]int)
if s == goal {
for i := 0; i < len(s); i++ {
if _, ok := mp[s[i]]; ok {
return true
}
mp[s[i]]++
}
return false
}
first, second := -1, -1
for i := 0; i < len(s); i++ {
if s[i] != goal[i] {
if first == -1 {
first = i
} else if second == -1 {
second = i
} else {
return false
}
}
}
return second != -1 && s[first] == goal[second] && s[second] == goal[first]
}
```

View File

@ -41,6 +41,11 @@ func Test_Problem875(t *testing.T) {
para875{[]int{30, 11, 23, 4, 20}, 6},
ans875{23},
},
{
para875{[]int{4, 9, 11, 17}, 8},
ans875{6},
},
}
fmt.Printf("------------------------Leetcode Problem 875------------------------\n")

View File

@ -0,0 +1,35 @@
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isCompleteTree(root *TreeNode) bool {
queue, found := []*TreeNode{root}, false
for len(queue) > 0 {
node := queue[0] //取出每一层的第一个节点
queue = queue[1:]
if node == nil {
found = true
} else {
if found {
return false // 层序遍历中,两个不为空的节点中出现一个 nil
}
//如果左孩子为nil则append进去的node.Left为nil
queue = append(queue, node.Left, node.Right)
}
}
return true
}

View File

@ -0,0 +1,51 @@
package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question958 struct {
para958
ans958
}
// para 是参数
// one 代表第一个参数
type para958 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans958 struct {
one bool
}
func Test_Problem958(t *testing.T) {
qs := []question958{
{
para958{[]int{1, 2, 3, 4, 5, 6}},
ans958{true},
},
{
para958{[]int{1, 2, 3, 4, 5, structures.NULL, 7}},
ans958{false},
},
}
fmt.Printf("------------------------Leetcode Problem 958------------------------\n")
for _, q := range qs {
_, p := q.ans958, q.para958
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", isCompleteTree(root))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,89 @@
# [958. Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/)
## 题目
Given the `root` of a binary tree, determine if it is a *complete binary tree*.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
![https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png)
```
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
```
**Example 2:**
![https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png)
```
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
```
**Constraints:**
- The number of nodes in the tree is in the range `[1, 100]`.
- `1 <= Node.val <= 1000`
## 题目大意
给定一个二叉树,确定它是否是一个完全二叉树。
百度百科中对完全二叉树的定义如下:
若设二叉树的深度为 h除第 h 层外,其它各层 (1h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。(注:第 h 层可能包含 1~ 2h 个节点。
## 解题思路
- 这一题是按层序遍历的变种题。
- 判断每个节点的左孩子是否为空。
- 类似的题目,第 102107199 题都是按层序遍历的。
## 代码
```go
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isCompleteTree(root *TreeNode) bool {
queue, found := []*TreeNode{root}, false
for len(queue) > 0 {
node := queue[0] //取出每一层的第一个节点
queue = queue[1:]
if node == nil {
found = true
} else {
if found {
return false // 层序遍历中,两个不为空的节点中出现一个 nil
}
//如果左孩子为nil则append进去的node.Left为nil
queue = append(queue, node.Left, node.Right)
}
}
return true
}
```

View File

@ -1,14 +1,14 @@
package leetcode
// 解法一 模拟法
func maxTurbulenceSize(A []int) int {
func maxTurbulenceSize(arr []int) int {
inc, dec := 1, 1
maxLen := min(1, len(A))
for i := 1; i < len(A); i++ {
if A[i-1] < A[i] {
maxLen := min(1, len(arr))
for i := 1; i < len(arr); i++ {
if arr[i-1] < arr[i] {
inc = dec + 1
dec = 1
} else if A[i-1] > A[i] {
} else if arr[i-1] > arr[i] {
dec = inc + 1
inc = 1
} else {
@ -35,23 +35,21 @@ func min(a int, b int) int {
}
// 解法二 滑动窗口
func maxTurbulenceSize1(A []int) int {
if len(A) == 1 {
return 1
}
// flag > 0 代表下一个数要大于前一个数flag < 0 代表下一个数要小于前一个数
res, left, right, flag, lastNum := 0, 0, 0, A[1]-A[0], A[0]
for left < len(A) {
if right < len(A)-1 && ((A[right+1] > lastNum && flag > 0) || (A[right+1] < lastNum && flag < 0) || (right == left)) {
right++
flag = lastNum - A[right]
lastNum = A[right]
func maxTurbulenceSize1(arr []int) int {
var maxLength int
if len(arr) == 2 && arr[0] != arr[1] {
maxLength = 2
} else {
if flag != 0 {
res = max(res, right-left+1)
maxLength = 1
}
left++
left := 0
for right := 2; right < len(arr); right++ {
if arr[right] == arr[right-1] {
left = right
} else if (arr[right]-arr[right-1])^(arr[right-1]-arr[right-2]) >= 0 {
left = right - 1
}
maxLength = max(maxLength, right-left+1)
}
return max(res, 1)
return maxLength
}

View File

@ -55,4 +55,4 @@ Return the **length** of a maximum size turbulent subarray of A.
- 给出一个数组要求找出摆动数组的最大长度所谓摆动数组的意思是元素一大一小间隔的
- 这一题可以用滑动窗口来解答一个变量记住下次出现的元素需要大于还是需要小于前一个元素也可以用模拟的方法用两个变量分别记录上升和下降数字的长度一旦元素相等了上升和下降数字长度都置为 1其他时候按照上升和下降的关系增加队列长度即可最后输出动态维护的最长长度
- 这一题可以用滑动窗口来解答相邻元素差的乘积大于零a ^ b >= 0 说明a b乘积大于零来判断是否是湍流 如果是那么扩大窗口。否则窗口缩小为0开始新的一个窗口。

View File

@ -1,10 +1,10 @@
package leetcode
/*
匹配跟单词中的字母顺序字母个数都无关可以用bitmap压缩
1. 记录word中 利用map记录各种bit标示的个数
2. puzzles 中各个字母都不相同! 记录bitmap然后搜索子空间中各种bit标识的个数的和
因为puzzles长度最长是7所以搜索空间 2^7
匹配跟单词中的字母顺序,字母个数都无关,可以用 bitmap 压缩
1. 记录 word 中 利用 map 记录各种 bit 标示的个数
2. puzzles 中各个字母都不相同! 记录 bitmap然后搜索子空间中各种 bit 标识的个数的和
因为 puzzles 长度最长是7所以搜索空间 2^7
*/
func findNumOfValidWords(words []string, puzzles []string) []int {
wordBitStatusMap, res := make(map[uint32]int, 0), []int{}
@ -14,7 +14,7 @@ func findNumOfValidWords(words []string, puzzles []string) []int {
for _, p := range puzzles {
var bitMap uint32
var totalNum int
bitMap |= (1 << (p[0] - 'a')) //work中要包含 p 的第一个字母 所以这个bit位上必须是1
bitMap |= (1 << (p[0] - 'a')) //work 中要包含 p 的第一个字母 所以这个 bit 位上必须是 1
findNum([]byte(p)[1:], bitMap, &totalNum, wordBitStatusMap)
res = append(res, totalNum)
}
@ -29,15 +29,15 @@ func toBitMap(word []byte) uint32 {
return res
}
//利用dfs 搜索 pussles的子空间
//利用 dfs 搜索 puzzles 的子空间
func findNum(puzzles []byte, bitMap uint32, totalNum *int, m map[uint32]int) {
if len(puzzles) == 0 {
*totalNum = *totalNum + m[bitMap]
return
}
//不包含puzzles[0],即puzzles[0]对应bit0
//不包含 puzzles[0],即 puzzles[0] 对应 bit0
findNum(puzzles[1:], bitMap, totalNum, m)
//包含puzzles[0],即puzzles[0]对应bit1
//包含 puzzles[0],即 puzzles[0] 对应 bit1
bitMap |= (1 << (puzzles[0] - 'a'))
findNum(puzzles[1:], bitMap, totalNum, m)
bitMap ^= (1 << (puzzles[0] - 'a')) //异或 清零

View File

@ -68,13 +68,14 @@ There're no valid words for "gaswxyz" cause none of the words in the list cont
## 代码
```go
package leetcode
/*
匹配跟单词中的字母顺序字母个数都无关可以用bitmap压缩
1. 记录word中 利用map记录各种bit标示的个数
2. puzzles 中各个字母都不相同! 记录bitmap然后搜索子空间中各种bit标识的个数的和
因为puzzles长度最长是7所以搜索空间 2^7
匹配跟单词中的字母顺序,字母个数都无关,可以用 bitmap 压缩
1. 记录 word 中 利用 map 记录各种 bit 标示的个数
2. puzzles 中各个字母都不相同! 记录 bitmap然后搜索子空间中各种 bit 标识的个数的和
因为 puzzles 长度最长是7所以搜索空间 2^7
*/
func findNumOfValidWords(words []string, puzzles []string) []int {
wordBitStatusMap, res := make(map[uint32]int, 0), []int{}
@ -84,7 +85,7 @@ func findNumOfValidWords(words []string, puzzles []string) []int {
for _, p := range puzzles {
var bitMap uint32
var totalNum int
bitMap |= (1 << (p[0] - 'a')) //work中要包含 p 的第一个字母 所以这个bit位上必须是1
bitMap |= (1 << (p[0] - 'a')) //work 中要包含 p 的第一个字母 所以这个 bit 位上必须是 1
findNum([]byte(p)[1:], bitMap, &totalNum, wordBitStatusMap)
res = append(res, totalNum)
}
@ -99,18 +100,20 @@ func toBitMap(word []byte) uint32 {
return res
}
//利用dfs 搜索 pussles的子空间
//利用 dfs 搜索 puzzles 的子空间
func findNum(puzzles []byte, bitMap uint32, totalNum *int, m map[uint32]int) {
if len(puzzles) == 0 {
*totalNum = *totalNum + m[bitMap]
return
}
//不包含puzzles[0],即puzzles[0]对应bit0
//不包含 puzzles[0],即 puzzles[0] 对应 bit0
findNum(puzzles[1:], bitMap, totalNum, m)
//包含puzzles[0],即puzzles[0]对应bit1
//包含 puzzles[0],即 puzzles[0] 对应 bit1
bitMap |= (1 << (puzzles[0] - 'a'))
findNum(puzzles[1:], bitMap, totalNum, m)
bitMap ^= (1 << (puzzles[0] - 'a')) //异或 清零
return
}
```

View File

@ -49,7 +49,7 @@ bool isPrime (int n){
上面这段代码的时间复杂度是 O(sqrt(n)) 而不是 O(n)。
再举一个例子,有一个字符串数组,将数组中的每一个字符串按照字母序排序,之后再整个字符串数组按照字典序排序。两步操作的整体时间复杂度是多少呢?
再举一个例子,有一个字符串数组,将数组中的每一个字符串按照字母序排序,之后再整个字符串数组按照字典序排序。两步操作的整体时间复杂度是多少呢?
如果回答是 O(n*nlog n + nlog n) = O(n^2log n),这个答案是错误的。字符串的长度和数组的长度是没有关系的,所以这两个变量应该单独计算。假设最长的字符串长度为 s数组中有 n 个字符串。对每个字符串排序的时间复杂度是 O(slog s),将数组中每个字符串都按照字母序排序的时间复杂度是 O(n * slog s)。

View File

@ -135,5 +135,5 @@ func romanToInt(s string) int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0012.Integer-to-Roman/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0015.3Sum/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0014.Longest-Common-Prefix/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,71 @@
# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)
## 题目
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
**Example 1**:
Input: strs = ["flower","flow","flight"]
Output: "fl"
**Example 2**:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
**Constraints:**
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
## 题目大意
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
## 解题思路
- 对 strs 按照字符串长度进行升序排序,求出 strs 中长度最小字符串的长度 minLen
- 逐个比较长度最小字符串与其它字符串中的字符,如果不相等就返回 commonPrefix,否则就把该字符加入 commonPrefix
## 代码
```go
package leetcode
import "sort"
func longestCommonPrefix(strs []string) string {
sort.Slice(strs, func(i, j int) bool {
return len(strs[i]) <= len(strs[j])
})
minLen := len(strs[0])
if minLen == 0 {
return ""
}
var commonPrefix []byte
for i := 0; i < minLen; i++ {
for j := 1; j < len(strs); j++ {
if strs[j][i] != strs[0][i] {
return string(commonPrefix)
}
}
commonPrefix = append(commonPrefix, strs[0][i])
}
return string(commonPrefix)
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0013.Roman-to-Integer/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0015.3Sum/">下一页➡️</a></p>
</div>

View File

@ -120,6 +120,6 @@ func threeSum1(nums []int) [][]int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0013.Roman-to-Integer/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0014.Longest-Common-Prefix/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0016.3Sum-Closest/">下一页➡️</a></p>
</div>

View File

@ -57,6 +57,7 @@ Output: [1]
```go
package leetcode
// 解法一
func nextPermutation(nums []int) {
i, j := 0, 0
for i = len(nums) - 2; i >= 0; i-- {
@ -86,6 +87,47 @@ func reverse(nums *[]int, i, j int) {
func swap(nums *[]int, i, j int) {
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
}
// 解法二
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
func nextPermutation1(nums []int) {
var n = len(nums)
var pIdx = checkPermutationPossibility(nums)
if pIdx == -1 {
reverse(&nums, 0, n-1)
return
}
var rp = len(nums) - 1
// start from right most to leftward,find the first number which is larger than PIVOT
for rp > 0 {
if nums[rp] > nums[pIdx] {
swap(&nums, pIdx, rp)
break
} else {
rp--
}
}
// Finally, Reverse all elements which are right from pivot
reverse(&nums, pIdx+1, n-1)
}
// checkPermutationPossibility returns 1st occurrence Index where
// value is in decreasing order(from right to left)
// returns -1 if not found(it's already in its last permutation)
func checkPermutationPossibility(nums []int) (idx int) {
// search right to left for 1st number(from right) that is not in increasing order
var rp = len(nums) - 1
for rp > 0 {
if nums[rp-1] < nums[rp] {
idx = rp - 1
return idx
}
rp--
}
return -1
}
```

View File

@ -99,6 +99,7 @@ You have to rotate the image **[in-place](https://en.wikipedia.org/wiki/In-plac
```go
package leetcode
// 解法一
func rotate(matrix [][]int) {
length := len(matrix)
// rotate by diagonal 对角线变换
@ -114,6 +115,50 @@ func rotate(matrix [][]int) {
}
}
}
// 解法二
func rotate1(matrix [][]int) {
n := len(matrix)
if n == 1 {
return
}
/* rotate clock-wise = 1. transpose matrix => 2. reverse(matrix[i])
1 2 3 4 1 5 9 13 13 9 5 1
5 6 7 8 => 2 6 10 14 => 14 10 6 2
9 10 11 12 3 7 11 15 15 11 7 3
13 14 15 16 4 8 12 16 16 12 8 4
*/
for i := 0; i < n; i++ {
// transpose, i=rows, j=columns
// j = i+1, coz diagonal elements didn't change in a square matrix
for j := i + 1; j < n; j++ {
swap(matrix, i, j)
}
// reverse each row of the image
matrix[i] = reverse(matrix[i])
}
}
// swap changes original slice's i,j position
func swap(nums [][]int, i, j int) {
nums[i][j], nums[j][i] = nums[j][i], nums[i][j]
}
// reverses a row of image, matrix[i]
func reverse(nums []int) []int {
var lp, rp = 0, len(nums) - 1
for lp < rp {
nums[lp], nums[rp] = nums[rp], nums[lp]
lp++
rp--
}
return nums
}
```

View File

@ -78,5 +78,5 @@ func insert(intervals []Interval, newInterval Interval) []Interval {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0056.Merge-Intervals/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0059.Spiral-Matrix-II/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0058.Length-of-Last-Word/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,77 @@
# [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/)
## 题目
Given a string `s` consisting of some words separated by some number of spaces, return *the length of the **last** word in the string.*
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
```
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
```
**Example 2:**
```
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
```
**Example 3:**
```
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
```
**Constraints:**
- `1 <= s.length <= 104`
- `s` consists of only English letters and spaces `' '`.
- There will be at least one word in `s`.
## 题目大意
给你一个字符串 `s`,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。**单词** 是指仅由字母组成、不包含任何空格字符的最大子字符串。
## 解题思路
- 先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度。
## 代码
```go
package leetcode
func lengthOfLastWord(s string) int {
last := len(s) - 1
for last >= 0 && s[last] == ' ' {
last--
}
if last < 0 {
return 0
}
first := last
for first >= 0 && s[first] != ' ' {
first--
}
return last - first
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0057.Insert-Interval/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0059.Spiral-Matrix-II/">下一页➡️</a></p>
</div>

View File

@ -96,6 +96,6 @@ func generateMatrix(n int) [][]int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0057.Insert-Interval/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0058.Length-of-Last-Word/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0060.Permutation-Sequence/">下一页➡️</a></p>
</div>

View File

@ -26,7 +26,7 @@ Your algorithm should have a linear runtime complexity. Could you implement it w
## 解题思路
- 题目要求不能使用辅助空间,并且时间复杂度只能是线性的。
- 题目为什么要强调有一个数字出现一次其他的出现两次我们想到了异或运算的性质任何一个数字异或它自己都等于0。也就是说如果我们从头到尾依次异或数组中的每一个数字那么最终的结果刚好是那个只出现次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。
- 题目为什么要强调有一个数字出现一次其他的出现两次我们想到了异或运算的性质任何一个数字异或它自己都等于0。也就是说如果我们从头到尾依次异或数组中的每一个数字那么最终的结果刚好是那个只出现次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。
## 代码

View File

@ -54,6 +54,52 @@ func findWords(board [][]byte, words []string) []string {
return res
}
// these is 79 solution
var dir = [][]int{
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
}
func exist(board [][]byte, word string) bool {
visited := make([][]bool, len(board))
for i := 0; i < len(visited); i++ {
visited[i] = make([]bool, len(board[0]))
}
for i, v := range board {
for j := range v {
if searchWord(board, visited, word, 0, i, j) {
return true
}
}
}
return false
}
func isInBoard(board [][]byte, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}
func searchWord(board [][]byte, visited [][]bool, word string, index, x, y int) bool {
if index == len(word)-1 {
return board[x][y] == word[index]
}
if board[x][y] == word[index] {
visited[x][y] = true
for i := 0; i < 4; i++ {
nx := x + dir[i][0]
ny := y + dir[i][1]
if isInBoard(board, nx, ny) && !visited[nx][ny] && searchWord(board, visited, word, index+1, nx, ny) {
return true
}
}
visited[x][y] = false
}
return false
}
```

View File

@ -116,5 +116,5 @@ func (this *Codec) deserializeHelper() *TreeNode {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0290.Word-Pattern/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0300.Longest-Increasing-Subsequence/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0299.Bulls-and-Cows/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,121 @@
# [299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)
## 题目
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
**Example 1:**
```
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"
```
**Example 2:**
```
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
```
**Example 3:**
```
Input: secret = "1", guess = "0"
Output: "0A0B"
```
**Example 4:**
```
Input: secret = "1", guess = "1"
Output: "1A0B"
```
**Constraints:**
- 1 <= secret.length, guess.length <= 1000
- secret.length == guess.length
- secret and guess consist of digits only.
## 题目大意
你在和朋友一起玩 猜数字Bulls and Cows游戏该游戏规则如下
写出一个秘密数字,并请朋友猜这个数字是多少。朋友每猜测一次,你就会给他一个包含下述信息的提示:
猜测数字中有多少位属于数字和确切位置都猜对了(称为 "Bulls", 公牛),
有多少位属于数字猜对了但是位置不对(称为 "Cows", 奶牛)。也就是说,这次猜测中有多少位非公牛数字可以通过重新排列转换成公牛数字。
给你一个秘密数字secret 和朋友猜测的数字guess ,请你返回对朋友这次猜测的提示。
提示的格式为 "xAyB" x 是公牛个数, y 是奶牛个数A 表示公牛B表示奶牛。
请注意秘密数字和朋友猜测的数字都可能含有重复数字。
## 解题思路
- 计算下标一致并且对应下标的元素一致的个数,即 x
- secret 和 guess 分别去除 x 个公牛的元素,剩下 secret 和 guess 求共同的元素个数就是 y
- 把 x y 转换成字符串,分别与 "A" 和 "B" 进行拼接返回结果
## 代码
```go
package leetcode
import "strconv"
func getHint(secret string, guess string) string {
cntA, cntB := 0, 0
mpS := make(map[byte]int)
var strG []byte
n := len(secret)
var ans string
for i := 0; i < n; i++ {
if secret[i] == guess[i] {
cntA++
} else {
mpS[secret[i]] += 1
strG = append(strG, guess[i])
}
}
for _, v := range strG {
if _, ok := mpS[v]; ok {
if mpS[v] > 1 {
mpS[v] -= 1
} else {
delete(mpS, v)
}
cntB++
}
}
ans += strconv.Itoa(cntA) + "A" + strconv.Itoa(cntB) + "B"
return ans
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0297.Serialize-and-Deserialize-Binary-Tree/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0300.Longest-Increasing-Subsequence/">下一页➡️</a></p>
</div>

View File

@ -82,6 +82,6 @@ func lengthOfLIS1(nums []int) int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0297.Serialize-and-Deserialize-Binary-Tree/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0303.Range-Sum-Query-Immutable/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0299.Bulls-and-Cows/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0301.Remove-Invalid-Parentheses/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,138 @@
# [301. Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)
## 题目
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
**Example 1:**
Input: s = "()())()"
Output: ["(())()","()()()"]
**Example 2:**
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
**Example 3:**
Input: s = ")("
Output: [""]
**Constraints:**
- 1 <= s.length <= 25
- s consists of lowercase English letters and parentheses '(' and ')'.
- There will be at most 20 parentheses in s.
## 题目大意
给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。
返回所有可能的结果。答案可以按 任意顺序 返回。
说明:
- 1 <= s.length <= 25
- s 由小写英文字母以及括号 '(' 和 ')' 组成
- s 中至多含 20 个括号
## 解题思路
回溯和剪枝
- 计算最大得分数maxScore合法字符串的长度length左括号和右括号的移除次数lmoves,rmoves
- 加一个左括号的得分加1加一个右括号的得分减1
- 对于一个合法的字符串左括号等于右括号得分最终为0
- 搜索过程中出现以下任何一种情况都直接返回
- 得分值为负数
- 得分大于最大得分数
- 得分小于0
- lmoves小于0
- rmoves小于0
## 代码
```go
package leetcode
var (
res []string
mp map[string]int
n int
length int
maxScore int
str string
)
func removeInvalidParentheses(s string) []string {
lmoves, rmoves, lcnt, rcnt := 0, 0, 0, 0
for _, v := range s {
if v == '(' {
lmoves++
lcnt++
} else if v == ')' {
if lmoves != 0 {
lmoves--
} else {
rmoves++
}
rcnt++
}
}
n = len(s)
length = n - lmoves - rmoves
res = []string{}
mp = make(map[string]int)
maxScore = min(lcnt, rcnt)
str = s
backtrace(0, "", lmoves, rmoves, 0)
return res
}
func backtrace(i int, cur string, lmoves int, rmoves int, score int) {
if lmoves < 0 || rmoves < 0 || score < 0 || score > maxScore {
return
}
if lmoves == 0 && rmoves == 0 {
if len(cur) == length {
if _, ok := mp[cur]; !ok {
res = append(res, cur)
mp[cur] = 1
}
return
}
}
if i == n {
return
}
if str[i] == '(' {
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
backtrace(i+1, cur, lmoves-1, rmoves, score)
} else if str[i] == ')' {
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
backtrace(i+1, cur, lmoves, rmoves-1, score)
} else {
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0300.Longest-Increasing-Subsequence/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0303.Range-Sum-Query-Immutable/">下一页➡️</a></p>
</div>

View File

@ -112,6 +112,6 @@ func (ma *NumArray) SumRange(i int, j int) int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0300.Longest-Increasing-Subsequence/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0301.Remove-Invalid-Parentheses/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0304.Range-Sum-Query-2D-Immutable/">下一页➡️</a></p>
</div>

View File

@ -80,5 +80,5 @@ func maxProduct318(words []string) int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0315.Count-of-Smaller-Numbers-After-Self/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0322.Coin-Change/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0319.Bulb-Switcher/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,65 @@
# [319. Bulb Switcher](https://leetcode.com/problems/bulb-switcher/)
## 题目
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
Return the number of bulbs that are on after n rounds.
**Example 1:**
Input: n = 3
Output: 1
Explanation: At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.
**Example 2:**
Input: n = 0
Output: 0
**Example 3:**
Input: n = 1
Output: 1
## 题目大意
初始时有 n 个灯泡处于关闭状态。第一轮,你将会打开所有灯泡。接下来的第二轮,你将会每两个灯泡关闭一个。
第三轮,你每三个灯泡就切换一个灯泡的开关(即,打开变关闭,关闭变打开)。第 i 轮,你每 i 个灯泡就切换一个灯泡的开关。直到第 n 轮,你只需要切换最后一个灯泡的开关。
找出并返回 n 轮后有多少个亮着的灯泡。
## 解题思路
- 计算 1 到 n 中有奇数个约数的个数
- 1 到 n 中的某个数 x 有奇数个约数,也即 x 是完全平方数
- 计算 1 到 n 中完全平方数的个数 sqrt(n)
## 代码
```go
package leetcode
import "math"
func bulbSwitch(n int) int {
return int(math.Sqrt(float64(n)))
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0318.Maximum-Product-of-Word-Lengths/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0322.Coin-Change/">下一页➡️</a></p>
</div>

View File

@ -63,6 +63,6 @@ func coinChange(coins []int, amount int) int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0318.Maximum-Product-of-Word-Lengths/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0319.Bulb-Switcher/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0324.Wiggle-Sort-II/">下一页➡️</a></p>
</div>

View File

@ -35,7 +35,7 @@ Output: 2->3->6->7->1->5->4->NULL
## 解题思路
这道题思路也是一样的,分别把奇数和偶数都放在 2 个链表中,最后首尾拼接就是答案。
这道题思路也是一样的,分别把奇数节点和偶数节点都放在 2 个链表中,最后首尾拼接就是答案。
## 代码

View File

@ -75,5 +75,5 @@ func intersect(nums1 []int, nums2 []int) []int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0349.Intersection-of-Two-Arrays/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0354.Russian-Doll-Envelopes/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0352.Data-Stream-as-Disjoint-Intervals/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,115 @@
# [352. Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/)
## 题目
Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.
Implement the SummaryRanges class:
- SummaryRanges() Initializes the object with an empty stream.
- void addNum(int val) Adds the integer val to the stream.
- int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi].
**Example 1:**
Input
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
Output
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
Explanation
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // return [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
**Constraints**
- 0 <= val <= 10000
- At most 3 * 10000 calls will be made to addNum and getIntervals.
## 题目大意
给你一个由非负整数a1, a2, ..., an 组成的数据流输入,请你将到目前为止看到的数字总结为不相交的区间列表。
实现 SummaryRanges 类:
- SummaryRanges() 使用一个空数据流初始化对象。
- void addNum(int val) 向数据流中加入整数 val 。
- int[][] getIntervals() 以不相交区间[starti, endi] 的列表形式返回对数据流中整数的总结
## 解题思路
- 使用字典过滤掉重复的数字
- 把过滤后的数字放到nums中,并进行排序
- 使用nums构建不重复的区间
## 代码
```go
package leetcode
import "sort"
type SummaryRanges struct {
nums []int
mp map[int]int
}
func Constructor() SummaryRanges {
return SummaryRanges{
nums: []int{},
mp : map[int]int{},
}
}
func (this *SummaryRanges) AddNum(val int) {
if _, ok := this.mp[val]; !ok {
this.mp[val] = 1
this.nums = append(this.nums, val)
}
sort.Ints(this.nums)
}
func (this *SummaryRanges) GetIntervals() [][]int {
n := len(this.nums)
var ans [][]int
if n == 0 {
return ans
}
if n == 1 {
ans = append(ans, []int{this.nums[0], this.nums[0]})
return ans
}
start, end := this.nums[0], this.nums[0]
ans = append(ans, []int{start, end})
index := 0
for i := 1; i < n; i++ {
if this.nums[i] == end + 1 {
end = this.nums[i]
ans[index][1] = end
} else {
start, end = this.nums[i], this.nums[i]
ans = append(ans, []int{start, end})
index++
}
}
return ans
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0350.Intersection-of-Two-Arrays-II/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0354.Russian-Doll-Envelopes/">下一页➡️</a></p>
</div>

View File

@ -84,6 +84,6 @@ func maxEnvelopes(envelopes [][]int) int {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0350.Intersection-of-Two-Arrays-II/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0352.Data-Stream-as-Disjoint-Intervals/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0357.Count-Numbers-with-Unique-Digits/">下一页➡️</a></p>
</div>

View File

@ -138,5 +138,5 @@ func (p *pq) Pop() interface{} {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0377.Combination-Sum-IV/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0385.Mini-Parser/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0384.Shuffle-an-Array/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,89 @@
# [384.Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)
## 题目
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution class:
- Solution(int[] nums) Initializes the object with the integer array nums.
- int[] reset() Resets the array to its original configuration and returns it.
- int[] shuffle() Returns a random shuffling of the array.
**Example 1**:
Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
// Any permutation of [1,2,3] must be equally likely to be returned.
// Example: return [3, 1, 2]
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
**Constraints:**
- 1 <= nums.length <= 200
- -1000000 <= nums[i] <= 1000000
- All the elements of nums are unique.
- At most 5 * 10000 calls in total will be made to reset and shuffle.
## 题目大意
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
实现 Solution class:
- Solution(int[] nums) 使用整数数组 nums 初始化对象
- int[] reset() 重设数组到它的初始状态并返回
- int[] shuffle() 返回数组随机打乱后的结果
## 解题思路
- 使用 rand.Shuffle 进行数组随机打乱
## 代码
```go
package leetcode
import "math/rand"
type Solution struct {
nums []int
}
func Constructor(nums []int) Solution {
return Solution{
nums: nums,
}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.nums
}
/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
arr := make([]int, len(this.nums))
copy(arr, this.nums)
rand.Shuffle(len(arr), func(i, j int) {
arr[i], arr[j] = arr[j], arr[i]
})
return arr
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0378.Kth-Smallest-Element-in-a-Sorted-Matrix/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0385.Mini-Parser/">下一页➡️</a></p>
</div>

View File

@ -177,6 +177,6 @@ func deserialize(s string) *NestedInteger {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0378.Kth-Smallest-Element-in-a-Sorted-Matrix/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0384.Shuffle-an-Array/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0386.Lexicographical-Numbers/">下一页➡️</a></p>
</div>

View File

@ -51,5 +51,5 @@ func findTheDifference(s string, t string) byte {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0387.First-Unique-Character-in-a-String/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0392.Is-Subsequence/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0391.Perfect-Rectangle/">下一页➡️</a></p>
</div>

View File

@ -0,0 +1,121 @@
# [391. Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/)
## 题目
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
Return true if all the rectangles together form an exact cover of a rectangular region.
**Example1:**
![https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg)
Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]
Output: true
Explanation: All 5 rectangles together form an exact cover of a rectangular region.
**Example2:**
![https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg)
Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]
Output: false
Explanation: Because there is a gap between the two rectangular regions.
**Example3:**
![https://assets.leetcode.com/uploads/2021/03/27/perfectrec3-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perfectrec3-plane.jpg)
Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]
Output: false
Explanation: Because there is a gap in the top center.
**Example4:**
![https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg](https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg)
Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]
Output: false
Explanation: Because two of the rectangles overlap with each other.
**Constraints:**
- 1 <= rectangles.length <= 2 * 10000
- rectangles[i].length == 4
- -100000 <= xi, yi, ai, bi <= 100000
## 题目大意
给你一个数组 rectangles ,其中 rectangles[i] = [xi, yi, ai, bi] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (xi, yi) ,右上顶点是 (ai, bi) 。
如果所有矩形一起精确覆盖了某个矩形区域,则返回 true ;否则,返回 false 。
## 解题思路
- 矩形区域的面积等于所有矩形的面积之和并且满足矩形区域四角的顶点只能出现一次,且其余顶点的出现次数只能是两次或四次则返回 true,否则返回 false
## 代码
```go
package leetcode
type point struct {
x int
y int
}
func isRectangleCover(rectangles [][]int) bool {
minX, minY, maxA, maxB := rectangles[0][0], rectangles[0][1], rectangles[0][2], rectangles[0][3]
area := 0
cnt := make(map[point]int)
for _, v := range rectangles {
x, y, a, b := v[0], v[1], v[2], v[3]
area += (a - x) * (b - y)
minX = min(minX, x)
minY = min(minY, y)
maxA = max(maxA, a)
maxB = max(maxB, b)
cnt[point{x, y}]++
cnt[point{a, b}]++
cnt[point{x, b}]++
cnt[point{a, y}]++
}
if area != (maxA - minX) * (maxB - minY) ||
cnt[point{minX, minY}] != 1 || cnt[point{maxA, maxB}] != 1 ||
cnt[point{minX, maxB}] != 1 || cnt[point{maxA, minY}] != 1 {
return false
}
delete(cnt, point{minX, minY})
delete(cnt, point{maxA, maxB})
delete(cnt, point{minX, maxB})
delete(cnt, point{maxA, minY})
for _, v := range cnt {
if v != 2 && v != 4 {
return false
}
}
return true
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0389.Find-the-Difference/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0392.Is-Subsequence/">下一页➡️</a></p>
</div>

View File

@ -82,6 +82,6 @@ func isSubsequence1(s string, t string) bool {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0389.Find-the-Difference/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0391.Perfect-Rectangle/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0393.UTF-8-Validation/">下一页➡️</a></p>
</div>

View File

@ -186,5 +186,5 @@ func convert(gene string) uint32 {
----------------------------------------------
<div style="display: flex;justify-content: space-between;align-items: center;">
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0400~0499/0429.N-ary-Tree-Level-Order-Traversal/">⬅️上一页</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0400~0499/0435.Non-overlapping-Intervals/">下一页➡️</a></p>
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0400~0499/0434.Number-of-Segments-in-a-String/">下一页➡️</a></p>
</div>

Some files were not shown because too many files have changed in this diff Show More