添加 problem 95、204、387、409、463、500、575、594、599、645、705、706、748、771、811、819、884、953、961、970、1002、1078

This commit is contained in:
YDZ
2019-07-16 18:25:00 +08:00
parent d1b1f7bdf2
commit 659be9f45d
70 changed files with 2453 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func generateTrees(n int) []*TreeNode {
if n == 0 {
return []*TreeNode{}
}
return generateBSTree(1, n)
}
func generateBSTree(start, end int) []*TreeNode {
tree := []*TreeNode{}
if start > end {
tree = append(tree, nil)
return tree
}
left, right := []*TreeNode{}, []*TreeNode{}
for i := start; i <= end; i++ {
left = generateBSTree(start, i-1)
right = generateBSTree(i+1, end)
for _, l := range left {
for _, r := range right {
root := &TreeNode{Val: i, Left: l, Right: r}
tree = append(tree, root)
}
}
}
return tree
}

View File

@@ -0,0 +1,56 @@
package leetcode
import (
"fmt"
"testing"
)
type question95 struct {
para95
ans95
}
// para 是参数
// one 代表第一个参数
type para95 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans95 struct {
one []*TreeNode
}
func Test_Problem95(t *testing.T) {
qs := []question95{
question95{
para95{1},
ans95{[]*TreeNode{&TreeNode{Val: 1, Left: nil, Right: nil}}},
},
question95{
para95{3},
ans95{[]*TreeNode{
&TreeNode{Val: 1, Left: nil, Right: &TreeNode{Val: 3, Left: &TreeNode{Val: 2, Left: nil, Right: nil}, Right: nil}},
&TreeNode{Val: 1, Left: nil, Right: &TreeNode{Val: 2, Left: nil, Right: &TreeNode{Val: 3, Left: nil, Right: nil}}},
&TreeNode{Val: 3, Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: nil}, Right: nil},
&TreeNode{Val: 3, Left: &TreeNode{Val: 1, Left: nil, Right: &TreeNode{Val: 2, Left: nil, Right: nil}}, Right: nil},
&TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}},
}}},
}
fmt.Printf("------------------------Leetcode Problem 95------------------------\n")
for _, q := range qs {
_, p := q.ans95, q.para95
fmt.Printf("【input】:%v \n", p)
trees := generateTrees(p.one)
for _, t := range trees {
fmt.Printf("【output】:%v\n", Tree2Preorder(t))
}
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,35 @@
# [95. Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)
## 题目:
Given an integer *n*, generate all structurally unique **BST's** (binary search trees) that store values 1 ... *n*.
**Example:**
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
## 题目大意
给定一个整数 n生成所有由 1 ... n 为节点所组成的二叉搜索树。
## 解题思路
- 输出 1~n 元素组成的 BST 所有解。这一题递归求解即可。外层循环遍历 1~n 所有结点,作为根结点,内层双层递归分别求出左子树和右子树。

View File

@@ -0,0 +1,20 @@
package leetcode
func countPrimes(n int) int {
isNotPrime := make([]bool, n)
for i := 2; i*i < n; i++ {
if isNotPrime[i] {
continue
}
for j := i * i; j < n; j = j + i {
isNotPrime[j] = true
}
}
count := 0
for i := 2; i < n; i++ {
if !isNotPrime[i] {
count++
}
}
return count
}

View File

@@ -0,0 +1,52 @@
package leetcode
import (
"fmt"
"testing"
)
type question204 struct {
para204
ans204
}
// para 是参数
// one 代表第一个参数
type para204 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans204 struct {
one int
}
func Test_Problem204(t *testing.T) {
qs := []question204{
question204{
para204{10},
ans204{4},
},
question204{
para204{100},
ans204{25},
},
question204{
para204{1000},
ans204{168},
},
}
fmt.Printf("------------------------Leetcode Problem 204------------------------\n")
for _, q := range qs {
_, p := q.ans204, q.para204
fmt.Printf("【input】:%v 【output】:%v\n", p, countPrimes(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,22 @@
# [204. Count Primes](https://leetcode.com/problems/count-primes/)
## 题目:
Count the number of prime numbers less than a non-negative number, **n**.
**Example:**
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
## 题目大意
统计所有小于非负整数 n 的质数的数量。
## 解题思路
- 给出一个数字 n要求输出小于 n 的所有素数的个数总和。简单题。

View File

@@ -0,0 +1,26 @@
# [387. First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)
## 题目:
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
**Examples:**
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
**Note:** You may assume the string contain only lowercase letters.
## 题目大意
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
## 解题思路
- 简单题,要求输出第一个没有重复的字符。

View File

@@ -0,0 +1,16 @@
package leetcode
func longestPalindrome(s string) int {
counter := make(map[rune]int)
for _, r := range s {
counter[r]++
}
answer := 0
for _, v := range counter {
answer += v / 2 * 2
if answer%2 == 0 && v%2 == 1 {
answer++
}
}
return answer
}

View File

@@ -0,0 +1,42 @@
package leetcode
import (
"fmt"
"testing"
)
type question409 struct {
para409
ans409
}
// para 是参数
// one 代表第一个参数
type para409 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans409 struct {
one int
}
func Test_Problem409(t *testing.T) {
qs := []question409{
question409{
para409{"abccccdd"},
ans409{7},
},
}
fmt.Printf("------------------------Leetcode Problem 409------------------------\n")
for _, q := range qs {
_, p := q.ans409, q.para409
fmt.Printf("【input】:%v 【output】:%v\n", p, longestPalindrome(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,33 @@
# [409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome/)
## 题目:
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example `"Aa"` is not considered a palindrome here.
**Note:**Assume the length of given string will not exceed 1,010.
**Example:**
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
## 题目大意
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。注意:假设字符串的长度不会超过 1010。
## 解题思路
- 给出一个字符串,要求用这个字符串里面的字符组成一个回文串,问回文串最长可以组合成多长的?
- 这也是一题水题,先统计每个字符的频次,然后每个字符能取 2 个的取 2 个,不足 2 个的并且当前构造中的回文串是偶数的情况下(即每 2 个都配对了),可以取 1 个。最后组合出来的就是最长回文串。

View File

@@ -0,0 +1,24 @@
package leetcode
func islandPerimeter(grid [][]int) int {
counter := 0
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == 1 {
if i-1 < 0 || grid[i-1][j] == 0 {
counter++
}
if i+1 >= len(grid) || grid[i+1][j] == 0 {
counter++
}
if j-1 < 0 || grid[i][j-1] == 0 {
counter++
}
if j+1 >= len(grid[0]) || grid[i][j+1] == 0 {
counter++
}
}
}
}
return counter
}

View File

@@ -0,0 +1,42 @@
package leetcode
import (
"fmt"
"testing"
)
type question463 struct {
para463
ans463
}
// para 是参数
// one 代表第一个参数
type para463 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans463 struct {
one int
}
func Test_Problem463(t *testing.T) {
qs := []question463{
question463{
para463{[][]int{[]int{0, 1, 0, 0}, []int{1, 1, 1, 0}, []int{0, 1, 0, 0}, []int{1, 1, 0, 0}}},
ans463{16},
},
}
fmt.Printf("------------------------Leetcode Problem 463------------------------\n")
for _, q := range qs {
_, p := q.ans463, q.para463
fmt.Printf("【input】:%v 【output】:%v\n", p, islandPerimeter(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,39 @@
# [463. Island Perimeter](https://leetcode.com/problems/island-perimeter/)
## 题目:
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
**Example:**
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/island.png)
## 题目大意
给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。
网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。
## 解题思路
- 给出一个二维数组,二维数组中有一些连在一起的 1 ,这是一个岛屿,求这个岛屿的周长。
- 这是一道水题,判断四周边界的情况依次加一即可。

View File

@@ -0,0 +1,27 @@
package leetcode
import "strings"
func findWords500(words []string) []string {
rows := []string{"qwertyuiop", "asdfghjkl", "zxcvbnm"}
output := make([]string, 0)
for _, s := range words {
if len(s) == 0 {
continue
}
lowerS := strings.ToLower(s)
oneRow := false
for _, r := range rows {
if strings.ContainsAny(lowerS, r) {
oneRow = !oneRow
if !oneRow {
break
}
}
}
if oneRow {
output = append(output, s)
}
}
return output
}

View File

@@ -0,0 +1,42 @@
package leetcode
import (
"fmt"
"testing"
)
type question500 struct {
para500
ans500
}
// para 是参数
// one 代表第一个参数
type para500 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans500 struct {
one []string
}
func Test_Problem500(t *testing.T) {
qs := []question500{
question500{
para500{[]string{"Hello", "Alaska", "Dad", "Peace"}},
ans500{[]string{"Alaska", "Dad"}},
},
}
fmt.Printf("------------------------Leetcode Problem 500------------------------\n")
for _, q := range qs {
_, p := q.ans500, q.para500
fmt.Printf("【input】:%v 【output】:%v\n", p, findWords500(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,27 @@
# [500. Keyboard Row](https://leetcode.com/problems/keyboard-row/)
## 题目:
Given a List of words, return the words that can be typed using letters of **alphabet** on only one row's of American keyboard like the image below.
![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/keyboard.png)
**Example:**
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
**Note:**
1. You may use one character in the keyboard more than once.
2. You may assume the input string will only contain letters of alphabet.
## 题目大意
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如上图所示。
## 解题思路
- 给出一个字符串数组,要求依次判断数组中的每个字符串是否都位于键盘上的同一个行,如果是就输出。这也是一道水题。

View File

@@ -0,0 +1,13 @@
package leetcode
func distributeCandies(candies []int) int {
n, m := len(candies), make(map[int]struct{}, len(candies))
for _, candy := range candies {
m[candy] = struct{}{}
}
res := len(m)
if n/2 < res {
return n / 2
}
return res
}

View File

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

View File

@@ -0,0 +1,38 @@
# [575. Distribute Candies](https://leetcode.com/problems/distribute-candies/)
## 题目:
Given an integer array with **even** length, where different numbers in this array represent different **kinds** of candies. Each number means one candy of the corresponding kind. You need to distribute these candies **equally** in number to brother and sister. Return the maximum number of **kinds** of candies the sister could gain.
**Example 1:**
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
The sister has three different kinds of candies.
**Example 2:**
Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
The sister has two different kinds of candies, the brother has only one kind of candies.
**Note:**
1. The length of the given array is in range [2, 10,000], and will be even.
2. The number in given array is in range [-100,000, 100,000].
## 题目大意
给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
## 解题思路
- 给出一个糖果数组,里面每个元素代表糖果的种类,相同数字代表相同种类。把这些糖果分给兄弟姐妹,问姐妹最多可以分到多少种糖果。这一题比较简单,用 map 统计每个糖果的出现频次,如果总数比 `n/2` 小,那么就返回 `len(map)`,否则返回 `n/2` (即一半都分给姐妹)。

View File

@@ -0,0 +1,24 @@
package leetcode
func findLHS(nums []int) int {
if len(nums) < 2 {
return 0
}
res := make(map[int]int, len(nums))
for _, num := range nums {
if _, exist := res[num]; exist {
res[num]++
continue
}
res[num] = 1
}
longest := 0
for k, c := range res {
if n, exist := res[k+1]; exist {
if c+n > longest {
longest = c + n
}
}
}
return longest
}

View File

@@ -0,0 +1,42 @@
package leetcode
import (
"fmt"
"testing"
)
type question594 struct {
para594
ans594
}
// para 是参数
// one 代表第一个参数
type para594 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans594 struct {
one int
}
func Test_Problem594(t *testing.T) {
qs := []question594{
question594{
para594{[]int{1, 3, 2, 2, 5, 2, 3, 7}},
ans594{5},
},
}
fmt.Printf("------------------------Leetcode Problem 594------------------------\n")
for _, q := range qs {
_, p := q.ans594, q.para594
fmt.Printf("【input】:%v 【output】:%v\n", p, findLHS(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,25 @@
# [594. Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence/)
## 题目:
We define a harmounious array as an array where the difference between its maximum value and its minimum value is **exactly** 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible [subsequences](https://en.wikipedia.org/wiki/Subsequence).
**Example 1:**
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
**Note:** The length of the input array will not exceed 20,000.
## 题目大意
和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。现在给定一个整数数组你需要在所有可能的子序列中找到最长的和谐子序列的长度。说明: 输入的数组长度最大不超过20,000.
## 解题思路
- 在给出的数组里面找到这样一个子数组:要求子数组中的最大值和最小值相差 1 。这一题是简单题。先统计每个数字出现的频次,然后在 map 找相差 1 的 2 个数组的频次和,动态的维护两个数的频次和就是最后要求的子数组的最大长度。

View File

@@ -0,0 +1,19 @@
package leetcode
func findRestaurant(list1 []string, list2 []string) []string {
m, ans := make(map[string]int, len(list1)), []string{}
for i, r := range list1 {
m[r] = i
}
for j, r := range list2 {
if _, ok := m[r]; ok {
m[r] += j
if len(ans) == 0 || m[r] == m[ans[0]] {
ans = append(ans, r)
} else if m[r] < m[ans[0]] {
ans = []string{r}
}
}
}
return ans
}

View File

@@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question599 struct {
para599
ans599
}
// para 是参数
// one 代表第一个参数
type para599 struct {
one []string
two []string
}
// ans 是答案
// one 代表第一个答案
type ans599 struct {
one []string
}
func Test_Problem599(t *testing.T) {
qs := []question599{
question599{
para599{[]string{"Shogun", "Tapioca Express", "Burger King", "KFC"}, []string{"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"}},
ans599{[]string{"Shogun"}},
},
question599{
para599{[]string{"Shogun", "Tapioca Express", "Burger King", "KFC"}, []string{"KFC", "Shogun", "Burger King"}},
ans599{[]string{"Shogun"}},
},
}
fmt.Printf("------------------------Leetcode Problem 599------------------------\n")
for _, q := range qs {
_, p := q.ans599, q.para599
fmt.Printf("【input】:%v 【output】:%v\n", p, findRestaurant(p.one, p.two))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,50 @@
# [599. Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/)
## 题目:
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their **common interest** with the **least list index sum**. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
**Example 1:**
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
**Example 2:**
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
**Note:**
1. The length of both lists will be in the range of [1, 1000].
2. The length of strings in both lists will be in the range of [1, 30].
3. The index is starting from 0 to the list length minus 1.
4. No duplicates in both lists.
## 题目大意
假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。
提示:
- 两个列表的长度范围都在 [1, 1000] 内。
- 两个列表中的字符串的长度将在 [130] 的范围内。
- 下标从 0 开始,到列表的长度减 1。
- 两个列表都没有重复的元素。
## 解题思路
- 在 Andy 和 Doris 两人分别有各自的餐厅喜欢列表,要求找出两人公共喜欢的一家餐厅,如果共同喜欢的次数相同,都输出。这一题是简单题,用 map 统计频次,输出频次最多的餐厅。

View File

@@ -0,0 +1,19 @@
package leetcode
func findErrorNums(nums []int) []int {
m, res := make([]int, len(nums)), make([]int, 2)
for _, n := range nums {
if m[n-1] == 0 {
m[n-1] = 1
} else {
res[0] = n
}
}
for i := range m {
if m[i] == 0 {
res[1] = i + 1
break
}
}
return res
}

View File

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

View File

@@ -0,0 +1,35 @@
# [645. Set Mismatch](https://leetcode.com/problems/set-mismatch/)
## 题目:
The set `S` originally contains numbers from 1 to `n`. But unfortunately, due to the data error, one of the numbers in the set got duplicated to **another** number in the set, which results in repetition of one number and loss of another number.
Given an array `nums` representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
**Example 1:**
Input: nums = [1,2,2,4]
Output: [2,3]
**Note:**
1. The given array size will in the range [2, 10000].
2. The given array's numbers won't have any order.
## 题目大意
集合 S 包含从1到 n 的整数。不幸的是因为数据错误导致集合里面某一个元素复制了成了集合里面的另外一个元素的值导致集合丢失了一个整数并且有一个元素重复。给定一个数组 nums 代表了集合 S 发生错误后的结果。你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
注意:
- 给定数组的长度范围是 [2, 10000]。
- 给定的数组是无序的。
## 解题思路
- 给出一个数组,数组里面装的是 1-n 的数字,由于错误导致有一个数字变成了另外一个数字,要求找出重复的一个数字和正确的数字。这一题是简单题,根据下标比对就可以找到哪个数字重复了,哪个数字缺少了。

View File

@@ -0,0 +1,33 @@
package leetcode
type MyHashSet struct {
data []bool
}
/** Initialize your data structure here. */
func Constructor705() MyHashSet {
return MyHashSet{
data: make([]bool, 1000001),
}
}
func (this *MyHashSet) Add(key int) {
this.data[key] = true
}
func (this *MyHashSet) Remove(key int) {
this.data[key] = false
}
/** Returns true if this set contains the specified element */
func (this *MyHashSet) Contains(key int) bool {
return this.data[key]
}
/**
* Your MyHashSet object will be instantiated and called as such:
* obj := Constructor();
* obj.Add(key);
* obj.Remove(key);
* param_3 := obj.Contains(key);
*/

View File

@@ -0,0 +1,24 @@
package leetcode
import (
"fmt"
"testing"
)
func Test_Problem705(t *testing.T) {
obj := Constructor705()
obj.Add(7)
fmt.Printf("Contains 7 = %v\n", obj.Contains(7))
obj.Remove(10)
fmt.Printf("Contains 10 = %v\n", obj.Contains(10))
obj.Add(20)
fmt.Printf("Contains 20 = %v\n", obj.Contains(20))
obj.Remove(30)
fmt.Printf("Contains 30 = %v\n", obj.Contains(30))
obj.Add(8)
fmt.Printf("Contains 8 = %v\n", obj.Contains(8))
obj.Remove(8)
fmt.Printf("Contains 8 = %v\n", obj.Contains(8))
param1 := obj.Contains(7)
fmt.Printf("param1 = %v\n", param1)
}

View File

@@ -0,0 +1,53 @@
# [705. Design HashSet](https://leetcode.com/problems/design-hashset/)
## 题目:
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
- `add(value)`: Insert a value into the HashSet.
- `contains(value)` : Return whether the value exists in the HashSet or not.
- `remove(value)`: Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
**Example:**
MyHashSet hashSet = new MyHashSet();
hashSet.add(1);        
hashSet.add(2);        
hashSet.contains(1);    // returns true
hashSet.contains(3);    // returns false (not found)
hashSet.add(2);          
hashSet.contains(2);    // returns true
hashSet.remove(2);          
hashSet.contains(2);    // returns false (already removed)
**Note:**
- All values will be in the range of `[0, 1000000]`.
- The number of operations will be in the range of `[1, 10000]`.
- Please do not use the built-in HashSet library.
## 题目大意
不使用任何内建的哈希表库设计一个哈希集合具体地说,你的设计应该包含以下的功能:
- add(value):向哈希集合中插入一个值。
- contains(value) :返回哈希集合中是否存在这个值。
- remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
注意:
- 所有的值都在 [1, 1000000] 的范围内。
- 操作的总数目在 [1, 10000] 范围内。
- 不要使用内建的哈希集合库。
## 解题思路
- 简单题,设计一个 hashset 的数据结构,要求有 `add(value)``contains(value)``remove(value)`,这 3 个方法。

View File

@@ -0,0 +1,92 @@
package leetcode
const Len int = 100000
type MyHashMap struct {
content [Len]*HashNode
}
type HashNode struct {
key int
val int
next *HashNode
}
func (N *HashNode) Put(key int, value int) {
if N.key == key {
N.val = value
return
}
if N.next == nil {
N.next = &HashNode{key, value, nil}
return
}
N.next.Put(key, value)
}
func (N *HashNode) Get(key int) int {
if N.key == key {
return N.val
}
if N.next == nil {
return -1
}
return N.next.Get(key)
}
func (N *HashNode) Remove(key int) *HashNode {
if N.key == key {
p := N.next
N.next = nil
return p
}
if N.next != nil {
return N.next.Remove(key)
}
return nil
}
/** Initialize your data structure here. */
func Constructor706() MyHashMap {
return MyHashMap{}
}
/** value will always be non-negative. */
func (this *MyHashMap) Put(key int, value int) {
node := this.content[this.Hash(key)]
if node == nil {
this.content[this.Hash(key)] = &HashNode{key: key, val: value, next: nil}
return
}
node.Put(key, value)
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
func (this *MyHashMap) Get(key int) int {
HashNode := this.content[this.Hash(key)]
if HashNode == nil {
return -1
}
return HashNode.Get(key)
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
func (this *MyHashMap) Remove(key int) {
HashNode := this.content[this.Hash(key)]
if HashNode == nil {
return
}
this.content[this.Hash(key)] = HashNode.Remove(key)
}
func (this *MyHashMap) Hash(value int) int {
return value % Len
}
/**
* Your MyHashMap object will be instantiated and called as such:
* obj := Constructor();
* obj.Put(key,value);
* param_2 := obj.Get(key);
* obj.Remove(key);
*/

View File

@@ -0,0 +1,19 @@
package leetcode
import (
"fmt"
"testing"
)
func Test_Problem706(t *testing.T) {
obj := Constructor706()
obj.Put(7, 10)
fmt.Printf("Get 7 = %v\n", obj.Get(7))
obj.Put(7, 20)
fmt.Printf("Contains 7 = %v\n", obj.Get(7))
param1 := obj.Get(100)
fmt.Printf("param1 = %v\n", param1)
obj.Remove(7)
param1 = obj.Get(7)
fmt.Printf("param1 = %v\n", param1)
}

View File

@@ -0,0 +1,51 @@
# [706. Design HashMap](https://leetcode.com/problems/design-hashmap/)
## 题目:
Design a HashMap without using any built-in hash table libraries.
To be specific, your design should include these functions:
- `put(key, value)` : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.
- `get(key)`: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
- `remove(key)` : Remove the mapping for the value key if this map contains the mapping for the key.
**Example:**
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);          
hashMap.put(2, 2);        
hashMap.get(1);            // returns 1
hashMap.get(3);            // returns -1 (not found)
hashMap.put(2, 1);          // update the existing value
hashMap.get(2);            // returns 1
hashMap.remove(2);          // remove the mapping for 2
hashMap.get(2);            // returns -1 (not found)
**Note:**
- All keys and values will be in the range of `[0, 1000000]`.
- The number of operations will be in the range of `[1, 10000]`.
- Please do not use the built-in HashMap library.
## 题目大意
不使用任何内建的哈希表库设计一个哈希映射具体地说,你的设计应该包含以下的功能:
- put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
- get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回 -1。
- remove(key):如果映射中存在这个键,删除这个数值对。
注意:
- 所有的值都在 [1, 1000000] 的范围内。
- 操作的总数目在 [1, 10000] 范围内。
- 不要使用内建的哈希库。
## 解题思路
- 简单题,设计一个 hashmap 的数据结构,要求有 `put(key, value)``get(key)``remove(key)`,这 3 个方法。设计一个 map 主要需要处理哈希冲突,一般都是链表法解决冲突。

View File

@@ -0,0 +1,39 @@
package leetcode
import "unicode"
func shortestCompletingWord(licensePlate string, words []string) string {
lp := genCnter(licensePlate)
var ret string
for _, w := range words {
if match(lp, w) {
if len(w) < len(ret) || ret == "" {
ret = w
}
}
}
return ret
}
func genCnter(lp string) [26]int {
cnter := [26]int{}
for _, ch := range lp {
if unicode.IsLetter(ch) {
cnter[unicode.ToLower(ch)-'a']++
}
}
return cnter
}
func match(lp [26]int, w string) bool {
m := [26]int{}
for _, ch := range w {
m[ch-'a']++
}
for k, v := range lp {
if m[k] < v {
return false
}
}
return true
}

View File

@@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question748 struct {
para748
ans748
}
// para 是参数
// one 代表第一个参数
type para748 struct {
c string
w []string
}
// ans 是答案
// one 代表第一个答案
type ans748 struct {
one string
}
func Test_Problem748(t *testing.T) {
qs := []question748{
question748{
para748{"1s3 PSt", []string{"step", "steps", "stripe", "stepple"}},
ans748{"steps"},
},
question748{
para748{"1s3 456", []string{"looks", "pest", "stew", "show"}},
ans748{"pest"},
},
}
fmt.Printf("------------------------Leetcode Problem 748------------------------\n")
for _, q := range qs {
_, p := q.ans748, q.para748
fmt.Printf("【input】:%v 【output】:%v\n", p, shortestCompletingWord(p.c, p.w))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,55 @@
# [748. Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word/)
## 题目:
Find the minimum length word from a given dictionary `words`, which has all the letters from the string `licensePlate`. Such a word is said to complete the given string `licensePlate`
Here, for letters we ignore case. For example, `"P"` on the `licensePlate` still matches `"p"` on the word.
It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.
The license plate might have the same letter occurring multiple times. For example, given a `licensePlate` of `"PP"`, the word `"pair"` does not complete the `licensePlate`, but the word `"supper"` does.
**Example 1:**
Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
Explanation: The smallest length word that contains the letters "S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.
**Example 2:**
Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
Output: "pest"
Explanation: There are 3 smallest length words that contains the letters "s".
We return the one that occurred first.
**Note:**
1. `licensePlate` will be a string with length in range `[1, 7]`.
2. `licensePlate` will contain digits, spaces, or letters (uppercase or lowercase).
3. `words` will have a length in the range `[10, 1000]`.
4. Every `words[i]` will consist of lowercase letters, and have length in range `[1, 15]`.
## 题目大意
如果单词列表words中的一个单词包含牌照licensePlate中所有的字母那么我们称之为完整词。在所有完整词中最短的单词我们称之为最短完整词。
单词在匹配牌照中的字母时不区分大小写,比如牌照中的 "P" 依然可以匹配单词中的 "p" 字母。我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。牌照中可能包含多个相同的字符,比如说:对于牌照 "PP",单词 "pair" 无法匹配,但是 "supper" 可以匹配。
注意:
- 牌照licensePlate的长度在区域[1, 7]中。
- 牌照licensePlate将会包含数字、空格、或者字母大写和小写
- 单词列表words长度在区间 [10, 1000] 中。
- 每一个单词 words[i] 都是小写,并且长度在区间 [1, 15] 中。
## 解题思路
- 给出一个数组,要求找出能包含 `licensePlate` 字符串中所有字符的最短长度的字符串。如果最短长度的字符串有多个,输出 word 下标小的那个。这一题也是简单题,不过有 2 个需要注意的点,第一点,`licensePlate` 中可能包含 `Unicode` 任意的字符,所以要先把字母的字符筛选出来,第二点是题目中保证了一定存在一个最短的单词能满足题意,并且忽略大小写。具体做法按照题意模拟即可。

View File

@@ -0,0 +1,28 @@
package leetcode
import "strings"
// 解法一
func numJewelsInStones(J string, S string) int {
count := 0
for i := range S {
if strings.Contains(J, string(S[i])) {
count++
}
}
return count
}
// 解法二
func numJewelsInStones1(J string, S string) int {
cache, result := make(map[rune]bool), 0
for _, r := range J {
cache[r] = true
}
for _, r := range S {
if _, ok := cache[r]; ok {
result++
}
}
return result
}

View File

@@ -0,0 +1,47 @@
package leetcode
import (
"fmt"
"testing"
)
type question771 struct {
para771
ans771
}
// para 是参数
// one 代表第一个参数
type para771 struct {
one string
two string
}
// ans 是答案
// one 代表第一个答案
type ans771 struct {
one int
}
func Test_Problem771(t *testing.T) {
qs := []question771{
question771{
para771{"aA", "aAAbbbb"},
ans771{3},
},
question771{
para771{"z", "ZZ"},
ans771{0},
},
}
fmt.Printf("------------------------Leetcode Problem 771------------------------\n")
for _, q := range qs {
_, p := q.ans771, q.para771
fmt.Printf("【input】:%v 【output】:%v\n", p, numJewelsInStones(p.one, p.two))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,38 @@
# [771. Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/)
## 题目:
You're given strings `J` representing the types of stones that are jewels, and `S` representing the stones you have. Each character in `S` is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in `J` are guaranteed distinct, and all characters in `J` and `S` are letters. Letters are case sensitive, so `"a"` is considered a different type of stone from `"A"`.
**Example 1:**
Input: J = "aA", S = "aAAbbbb"
Output: 3
**Example 2:**
Input: J = "z", S = "ZZ"
Output: 0
**Note:**
- `S` and `J` will consist of letters and have length at most 50.
- The characters in `J` are distinct.
## 题目大意
给定字符串 J 代表石头中宝石的类型和字符串 S 代表你拥有的石头。S 中每个字符代表了一种你拥有的石头的类型你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复J  S 中的所有字符都是字母。字母区分大小写,因此 "a" 和 "A" 是不同类型的石头。
## 解题思路
- 给出 2 个字符串,要求在 S 字符串中找出在 J 字符串里面出现的字符个数。这是一道简单题。

View File

@@ -0,0 +1,84 @@
package leetcode
import (
"strconv"
"strings"
)
// 解法一
func subdomainVisits(cpdomains []string) []string {
result := make([]string, 0)
if len(cpdomains) == 0 {
return result
}
domainCountMap := make(map[string]int, 0)
for _, domain := range cpdomains {
countDomain := strings.Split(domain, " ")
allDomains := strings.Split(countDomain[1], ".")
temp := make([]string, 0)
for i := len(allDomains) - 1; i >= 0; i-- {
temp = append([]string{allDomains[i]}, temp...)
ld := strings.Join(temp, ".")
count, _ := strconv.Atoi(countDomain[0])
if val, ok := domainCountMap[ld]; !ok {
domainCountMap[ld] = count
} else {
domainCountMap[ld] = count + val
}
}
}
for k, v := range domainCountMap {
t := strings.Join([]string{strconv.Itoa(v), k}, " ")
result = append(result, t)
}
return result
}
// 解法二
func subdomainVisits1(cpdomains []string) []string {
out := make([]string, 0)
var b strings.Builder
domains := make(map[string]int, 0)
for _, v := range cpdomains {
splitDomain(v, domains)
}
for k, v := range domains {
b.WriteString(strconv.Itoa(v))
b.WriteString(" ")
b.WriteString(k)
out = append(out, b.String())
b.Reset()
}
return out
}
func splitDomain(domain string, domains map[string]int) {
visits := 0
var e error
subdomains := make([]string, 0)
for i, v := range domain {
if v == ' ' {
visits, e = strconv.Atoi(domain[0:i])
if e != nil {
panic(e)
}
break
}
}
for i := len(domain) - 1; i >= 0; i-- {
if domain[i] == '.' {
subdomains = append(subdomains, domain[i+1:])
} else if domain[i] == ' ' {
subdomains = append(subdomains, domain[i+1:])
break
}
}
for _, v := range subdomains {
count, ok := domains[v]
if ok {
domains[v] = count + visits
} else {
domains[v] = visits
}
}
}

View File

@@ -0,0 +1,47 @@
package leetcode
import (
"fmt"
"testing"
)
type question811 struct {
para811
ans811
}
// para 是参数
// one 代表第一个参数
type para811 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans811 struct {
one []string
}
func Test_Problem811(t *testing.T) {
qs := []question811{
question811{
para811{[]string{"9001 discuss.leetcode.com"}},
ans811{[]string{"mqe", "mqE", "mQe", "mQE", "Mqe", "MqE", "MQe", "MQE"}},
},
question811{
para811{[]string{"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"}},
ans811{[]string{"901 mail.com", "50 yahoo.com", "900 google.mail.com", "5 wiki.org", "5 org", "1 intel.mail.com", "951 com"}},
},
}
fmt.Printf("------------------------Leetcode Problem 811------------------------\n")
for _, q := range qs {
_, p := q.ans811, q.para811
fmt.Printf("【input】:%v 【output】:%v\n", p, subdomainVisits(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,49 @@
# [811. Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/)
## 题目:
A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".
We are given a list `cpdomains` of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.
Example 1:
Input:
["9001 discuss.leetcode.com"]
Output:
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Explanation:
We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Example 2:
Input:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation:
We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
**Notes:**
- The length of `cpdomains` will not exceed `100`.
- The length of each domain name will not exceed `100`.
- Each address will have either 1 or 2 "." characters.
- The input count in any count-paired domain will not exceed `10000`.
- The answer output can be returned in any order.
## 题目大意
一个网站域名,如 "discuss.leetcode.com",包含了多个子域名。作为顶级域名,常用的有 "com",下一级则有 "leetcode.com",最低的一级为 "discuss.leetcode.com"。当我们访问域名 "discuss.leetcode.com" 时,也同时访问了其父域名 "leetcode.com" 以及顶级域名 "com"。给定一个带访问次数和域名的组合,要求分别计算每个域名被访问的次数。其格式为访问次数+空格+地址,例如:"9001 discuss.leetcode.com"。
接下来会给出一组访问次数和域名组合的列表 cpdomains 。要求解析出所有域名的访问次数输出格式和输入格式相同不限定先后顺序。
## 解题思路
- 这一题是简单题,统计每个 domain 的出现频次。每个域名根据层级,一级一级的累加频次,比如 `discuss.leetcode.com``discuss.leetcode.com` 这个域名频次为 1`leetcode.com` 这个域名频次为 1`com` 这个域名频次为 1。用 map 依次统计每个 domain 出现的频次,按照格式要求输出。

View File

@@ -0,0 +1,37 @@
package leetcode
import "strings"
func mostCommonWord(paragraph string, banned []string) string {
freqMap, start := make(map[string]int), -1
for i, c := range paragraph {
if c == ' ' || c == '!' || c == '?' || c == '\'' || c == ',' || c == ';' || c == '.' {
if start > -1 {
word := strings.ToLower(paragraph[start:i])
freqMap[word]++
}
start = -1
} else {
if start == -1 {
start = i
}
}
}
if start != -1 {
word := strings.ToLower(paragraph[start:])
freqMap[word]++
}
// Strip the banned words from the freqmap
for _, bannedWord := range banned {
delete(freqMap, bannedWord)
}
// Find most freq word
mostFreqWord, mostFreqCount := "", 0
for word, freq := range freqMap {
if freq > mostFreqCount {
mostFreqWord = word
mostFreqCount = freq
}
}
return mostFreqWord
}

View File

@@ -0,0 +1,43 @@
package leetcode
import (
"fmt"
"testing"
)
type question819 struct {
para819
ans819
}
// para 是参数
// one 代表第一个参数
type para819 struct {
one string
b []string
}
// ans 是答案
// one 代表第一个答案
type ans819 struct {
one string
}
func Test_Problem819(t *testing.T) {
qs := []question819{
question819{
para819{"Bob hit a ball, the hit BALL flew far after it was hit.", []string{"hit"}},
ans819{"ball"},
},
}
fmt.Printf("------------------------Leetcode Problem 819------------------------\n")
for _, q := range qs {
_, p := q.ans819, q.para819
fmt.Printf("【input】:%v 【output】:%v\n", p, mostCommonWord(p.one, p.b))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,44 @@
# [819. Most Common Word](https://leetcode.com/problems/most-common-word/)
## 题目:
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
**Example:**
Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
**Note:**
- `1 <= paragraph.length <= 1000`.
- `0 <= banned.length <= 100`.
- `1 <= banned[i].length <= 10`.
- The answer is unique, and written in lowercase (even if its occurrences in `paragraph` may have uppercase symbols, and even if it is a proper noun.)
- `paragraph` only consists of letters, spaces, or the punctuation symbols `!?',;.`
- There are no hyphens or hyphenated words.
- Words only consist of letters, never apostrophes or other punctuation symbols.
## 题目大意
给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。题目保证至少有一个词不在禁用列表中,而且答案唯一。
禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。
## 解题思路
- 给出一段话和一个 banned 的字符串,要求输出这段话中出现频次最高的并且不出现在 banned 数组里面的字符串,答案唯一。这题是简单题,依次统计每个单词的频次,然后从 map 中删除 banned 里面的单词,取出剩下频次最高的单词即可。

View File

@@ -0,0 +1,18 @@
package leetcode
import "strings"
func uncommonFromSentences(A string, B string) []string {
m, res := map[string]int{}, []string{}
for _, s := range []string{A, B} {
for _, word := range strings.Split(s, " ") {
m[word]++
}
}
for key := range m {
if m[key] == 1 {
res = append(res, key)
}
}
return res
}

View File

@@ -0,0 +1,48 @@
package leetcode
import (
"fmt"
"testing"
)
type question884 struct {
para884
ans884
}
// para 是参数
// one 代表第一个参数
type para884 struct {
A string
B string
}
// ans 是答案
// one 代表第一个答案
type ans884 struct {
one []string
}
func Test_Problem884(t *testing.T) {
qs := []question884{
question884{
para884{"this apple is sweet", "this apple is sour"},
ans884{[]string{"sweet", "sour"}},
},
question884{
para884{"apple apple", "banana"},
ans884{[]string{"banana"}},
},
}
fmt.Printf("------------------------Leetcode Problem 884------------------------\n")
for _, q := range qs {
_, p := q.ans884, q.para884
fmt.Printf("【input】:%v 【output】:%v\n", p, uncommonFromSentences(p.A, p.B))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,40 @@
# [884. Uncommon Words from Two Sentences](https://leetcode.com/problems/uncommon-words-from-two-sentences/)
## 题目:
We are given two sentences `A` and `B`. (A *sentence* is a string of space separated words. Each *word* consists only of lowercase letters.)
A word is *uncommon* if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in any order.
**Example 1:**
Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]
**Example 2:**
Input: A = "apple apple", B = "banana"
Output: ["banana"]
**Note:**
1. `0 <= A.length <= 200`
2. `0 <= B.length <= 200`
3. `A` and `B` both contain only spaces and lowercase letters.
## 题目大意
给定两个句子 A  B 句子是一串由空格分隔的单词。每个单词仅由小写字母组成。
如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。返回所有不常用单词的列表。您可以按任何顺序返回列表。
## 解题思路
- 找出 2 个句子中不同的单词,将它们俩都打印出来。简单题,先将 2 个句子的单词都拆开放入 map 中进行词频统计,不同的两个单词的词频肯定都为 1输出它们即可。

View File

@@ -0,0 +1,28 @@
package leetcode
func isAlienSorted(words []string, order string) bool {
if len(words) < 2 {
return true
}
hash := make(map[byte]int)
for i := 0; i < len(order); i++ {
hash[order[i]] = i
}
for i := 0; i < len(words)-1; i++ {
pointer, word, wordplus := 0, words[i], words[i+1]
for pointer < len(word) && pointer < len(wordplus) {
if hash[word[pointer]] > hash[wordplus[pointer]] {
return false
}
if hash[word[pointer]] < hash[wordplus[pointer]] {
break
} else {
pointer = pointer + 1
}
}
if pointer < len(word) && pointer >= len(wordplus) {
return false
}
}
return true
}

View File

@@ -0,0 +1,52 @@
package leetcode
import (
"fmt"
"testing"
)
type question953 struct {
para953
ans953
}
// para 是参数
// one 代表第一个参数
type para953 struct {
one []string
two string
}
// ans 是答案
// one 代表第一个答案
type ans953 struct {
one bool
}
func Test_Problem953(t *testing.T) {
qs := []question953{
question953{
para953{[]string{"hello", "leetcode"}, "hlabcdefgijkmnopqrstuvwxyz"},
ans953{true},
},
question953{
para953{[]string{"word", "world", "row"}, "worldabcefghijkmnpqstuvxyz"},
ans953{false},
},
question953{
para953{[]string{"apple", "app"}, "abcdefghijklmnopqrstuvwxyz"},
ans953{false},
},
}
fmt.Printf("------------------------Leetcode Problem 953------------------------\n")
for _, q := range qs {
_, p := q.ans953, q.para953
fmt.Printf("【input】:%v 【output】:%v\n", p, isAlienSorted(p.one, p.two))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,45 @@
# [953. Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/)
## 题目:
In an alien language, surprisingly they also use english lowercase letters, but possibly in a different `order`. The `order`of the alphabet is some permutation of lowercase letters.
Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographicaly in this alien language.
**Example 1:**
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
**Example 2:**
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
**Example 3:**
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
**Note:**
1. `1 <= words.length <= 100`
2. `1 <= words[i].length <= 20`
3. `order.length == 26`
4. All characters in `words[i]` and `order` are english lowercase letters.
## 题目大意
某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序order是一些小写字母的排列。给定一组用外星语书写的单词 words以及其字母表的顺序 order只有当给定的单词在这种外星语中按字典序排列时返回 true否则返回 false。
## 解题思路
- 这一题是简单题。给出一个字符串数组,判断把字符串数组里面字符串是否是按照 order 的排序排列的。order 是给出个一个字符串排序。这道题的解法是把 26 个字母的顺序先存在 map 中,然后依次遍历判断字符串数组里面字符串的大小。

View File

@@ -0,0 +1,12 @@
package leetcode
func repeatedNTimes(A []int) int {
kv := make(map[int]struct{})
for _, val := range A {
if _, ok := kv[val]; ok {
return val
}
kv[val] = struct{}{}
}
return 0
}

View File

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

View File

@@ -0,0 +1,40 @@
# [961. N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/)
## 题目:
In a array `A` of size `2N`, there are `N+1` unique elements, and exactly one of these elements is repeated N times.
Return the element repeated `N` times.
**Example 1:**
Input: [1,2,3,3]
Output: 3
**Example 2:**
Input: [2,1,2,5,3,2]
Output: 2
**Example 3:**
Input: [5,1,5,2,5,3,5,4]
Output: 5
**Note:**
1. `4 <= A.length <= 10000`
2. `0 <= A[i] < 10000`
3. `A.length` is even
## 题目大意
在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。返回重复了 N 次的那个元素。
## 解题思路
- 简单题。数组中有 2N 个数,有 N + 1 个数是不重复的,这之中有一个数重复了 N 次,请找出这个数。解法非常简单,把所有数都存入 map 中,如果遇到存在的 key 就返回这个数。

View File

@@ -0,0 +1,35 @@
package leetcode
import "math"
func powerfulIntegers(x int, y int, bound int) []int {
if x == 1 && y == 1 {
if bound < 2 {
return []int{}
}
return []int{2}
}
if x > y {
x, y = y, x
}
visit, result := make(map[int]bool), make([]int, 0)
for i := 0; ; i++ {
found := false
for j := 0; pow(x, i)+pow(y, j) <= bound; j++ {
v := pow(x, i) + pow(y, j)
if !visit[v] {
found = true
visit[v] = true
result = append(result, v)
}
}
if !found {
break
}
}
return result
}
func pow(x, i int) int {
return int(math.Pow(float64(x), float64(i)))
}

View File

@@ -0,0 +1,49 @@
package leetcode
import (
"fmt"
"testing"
)
type question970 struct {
para970
ans970
}
// para 是参数
// one 代表第一个参数
type para970 struct {
one int
two int
b int
}
// ans 是答案
// one 代表第一个答案
type ans970 struct {
one []int
}
func Test_Problem970(t *testing.T) {
qs := []question970{
question970{
para970{2, 3, 10},
ans970{[]int{2, 3, 4, 5, 7, 9, 10}},
},
question970{
para970{3, 5, 15},
ans970{[]int{2, 4, 6, 8, 10, 14}},
},
}
fmt.Printf("------------------------Leetcode Problem 970------------------------\n")
for _, q := range qs {
_, p := q.ans970, q.para970
fmt.Printf("【input】:%v 【output】:%v\n", p, powerfulIntegers(p.one, p.two, p.b))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,45 @@
# [970. Powerful Integers](https://leetcode.com/problems/powerful-integers/)
## 题目:
Given two positive integers `x` and `y`, an integer is *powerful* if it is equal to `x^i + y^j` for some integers `i >= 0` and `j >= 0`.
Return a list of all *powerful* integers that have value less than or equal to `bound`.
You may return the answer in any order. In your answer, each value should occur at most once.
**Example 1:**
Input: x = 2, y = 3, bound = 10
Output: [2,3,4,5,7,9,10]
Explanation:
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
7 = 2^2 + 3^1
9 = 2^3 + 3^0
10 = 2^0 + 3^2
**Example 2:**
Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]
**Note:**
- `1 <= x <= 100`
- `1 <= y <= 100`
- `0 <= bound <= 10^6`
## 题目大意
给定两个正整数 x 和 y如果某一整数等于 x^i + y^j其中整数 i >= 0 且 j >= 0那么我们认为该整数是一个强整数。返回值小于或等于 bound 的所有强整数组成的列表。你可以按任何顺序返回答案。在你的回答中每个值最多出现一次。
## 解题思路
- 简答题,题目要求找出满足 `x^i + y^j ≤ bound` 条件的所有解。题目要求输出中不能重复,所以用 map 来去重。剩下的就是 `n^2` 暴力循环枚举所有解。

View File

@@ -0,0 +1,33 @@
package leetcode
import "math"
func commonChars(A []string) []string {
cnt := [26]int{}
for i := range cnt {
cnt[i] = math.MaxUint16
}
cntInWord := [26]int{}
for _, word := range A {
for _, char := range []byte(word) { // compiler trick - here we will not allocate new memory
cntInWord[char-'a']++
}
for i := 0; i < 26; i++ {
// 缩小频次,使得统计的公共频次更加准确
if cntInWord[i] < cnt[i] {
cnt[i] = cntInWord[i]
}
}
// 重置状态
for i := range cntInWord {
cntInWord[i] = 0
}
}
result := make([]string, 0)
for i := 0; i < 26; i++ {
for j := 0; j < cnt[i]; j++ {
result = append(result, string(i+'a'))
}
}
return result
}

View File

@@ -0,0 +1,47 @@
package leetcode
import (
"fmt"
"testing"
)
type question1002 struct {
para1002
ans1002
}
// para 是参数
// one 代表第一个参数
type para1002 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans1002 struct {
one []string
}
func Test_Problem1002(t *testing.T) {
qs := []question1002{
question1002{
para1002{[]string{"bella", "label", "roller"}},
ans1002{[]string{"e", "l", "l"}},
},
question1002{
para1002{[]string{"cool", "lock", "cook"}},
ans1002{[]string{"c", "o"}},
},
}
fmt.Printf("------------------------Leetcode Problem 1002------------------------\n")
for _, q := range qs {
_, p := q.ans1002, q.para1002
fmt.Printf("【input】:%v 【output】:%v\n", p, commonChars(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,33 @@
# [1002. Find Common Characters](https://leetcode.com/problems/find-common-characters/)
## 题目:
Given an array `A` of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list **(including duplicates)**. For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
**Example 1:**
Input: ["bella","label","roller"]
Output: ["e","l","l"]
**Example 2:**
Input: ["cool","lock","cook"]
Output: ["c","o"]
**Note:**
1. `1 <= A.length <= 100`
2. `1 <= A[i].length <= 100`
3. `A[i][j]` is a lowercase letter
## 题目大意
给定仅有小写字母组成的字符串数组 A返回列表中的每个字符串中都显示的全部字符包括重复字符组成的列表。例如如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。你可以按任意顺序返回答案。
## 解题思路
- 简单题。给出一个字符串数组 A要求找出这个数组中每个字符串都包含字符如果字符出现多次在最终结果中也需要出现多次。这一题可以用 map 来统计每个字符串的频次,但是如果用数组统计会更快。题目中说了只有小写字母,那么用 2 个 26 位长度的数组就可以统计出来了。遍历字符串数组的过程中,不过的缩小每个字符在每个字符串中出现的频次(因为需要找所有字符串公共的字符,公共的频次肯定就是最小的频次),得到了最终公共字符的频次数组以后,按顺序输出就可以了。

View File

@@ -0,0 +1,17 @@
package leetcode
import "strings"
func findOcurrences(text string, first string, second string) []string {
var res []string
words := strings.Split(text, " ")
if len(words) < 3 {
return []string{}
}
for i := 2; i < len(words); i++ {
if words[i-2] == first && words[i-1] == second {
res = append(res, words[i])
}
}
return res
}

View File

@@ -0,0 +1,49 @@
package leetcode
import (
"fmt"
"testing"
)
type question1078 struct {
para1078
ans1078
}
// para 是参数
// one 代表第一个参数
type para1078 struct {
t string
f string
s string
}
// ans 是答案
// one 代表第一个答案
type ans1078 struct {
one []string
}
func Test_Problem1078(t *testing.T) {
qs := []question1078{
question1078{
para1078{"alice is a good girl she is a good student", "a", "good"},
ans1078{[]string{"girl", "student"}},
},
question1078{
para1078{"we will we will rock you", "we", "will"},
ans1078{[]string{"we", "rock"}},
},
}
fmt.Printf("------------------------Leetcode Problem 1078------------------------\n")
for _, q := range qs {
_, p := q.ans1078, q.para1078
fmt.Printf("【input】:%v 【output】:%v\n", p, findOcurrences(p.t, p.f, p.s))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,39 @@
# [1078. Occurrences After Bigram](https://leetcode.com/problems/occurrences-after-bigram/)
## 题目:
Given words `first` and `second`, consider occurrences in some `text` of the form "`first second third`", where `second` comes immediately after `first`, and `third`comes immediately after `second`.
For each such occurrence, add "`third`" to the answer, and return the answer.
**Example 1:**
Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl","student"]
**Example 2:**
Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]
**Note:**
1. `1 <= text.length <= 1000`
2. `text` consists of space separated words, where each word consists of lowercase English letters.
3. `1 <= first.length, second.length <= 10`
4. `first` and `second` consist of lowercase English letters.
## 题目大意
给出第一个词 first 和第二个词 second考虑在某些文本 text 中可能以 "first second third" 形式出现的情况其中 second 紧随 first 出现third 紧随 second 出现。对于每种这样的情况将第三个词 "third" 添加到答案中,并返回答案。
## 解题思路
- 简单题。给出一个 text要求找出紧接在 first 和 second 后面的那个字符串,有多个就输出多个。解法很简单,先分解出 words 每个字符串,然后依次遍历进行字符串匹配。匹配到 first 和 second 以后,输出之后的那个字符串。