Skip to content

Commit 5d72b11

Browse files
Merge pull request #217 from hhf666feng/master
第四周作业#26
2 parents 542f201 + 7214c83 commit 5d72b11

12 files changed

+938
-0
lines changed

Week_04/id_26/LeetCode_169_26.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#
2+
# @lc app=leetcode.cn id=169 lang=python
3+
#
4+
# [169] 求众数
5+
#
6+
# https://leetcode-cn.com/problems/majority-element/description/
7+
#
8+
# algorithms
9+
# Easy (59.48%)
10+
# Likes: 261
11+
# Dislikes: 0
12+
# Total Accepted: 49.3K
13+
# Total Submissions: 82.6K
14+
# Testcase Example: '[3,2,3]'
15+
#
16+
# 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
17+
#
18+
# 你可以假设数组是非空的,并且给定的数组总是存在众数。
19+
#
20+
# 示例 1:
21+
#
22+
# 输入: [3,2,3]
23+
# 输出: 3
24+
#
25+
# 示例 2:
26+
#
27+
# 输入: [2,2,1,1,1,2,2]
28+
# 输出: 2
29+
#
30+
#
31+
#
32+
33+
34+
class Solution(object):
35+
def majorityElement1(self, nums):
36+
"""
37+
:type nums: List[int]
38+
:rtype: int
39+
解法1:排序
40+
"""
41+
nums.sort()
42+
return nums[len(nums)//2]
43+
44+
def majorityElement(self, nums):
45+
"""
46+
:type nums: List[int]
47+
:rtype: int
48+
解法2: 递归+分治
49+
分治问题模板步骤:
50+
1.结束条件
51+
2.拆分子问题
52+
3.递归处理子问题
53+
4.处理子问题的结果
54+
"""
55+
def helper(left, right):
56+
57+
if left == right:
58+
return nums[left]
59+
60+
mid = (right+left) // 2
61+
62+
leftNum = helper(left, mid)
63+
rightNum = helper(mid+1, right)
64+
65+
if leftNum == rightNum:
66+
return leftNum
67+
leftCount, rightCount = 0, 0
68+
for i in range(left, right+1):
69+
if nums[i] == leftNum:
70+
leftCount += 1
71+
elif nums[i] == rightNum:
72+
rightCount += 1
73+
return leftNum if leftCount >= rightCount else rightNum
74+
75+
return helper(0, len(nums)-1)
76+
77+
78+
# print(Solution().majorityElement([1, 2, 1, 3, 1, 2, 1]))

Week_04/id_26/LeetCode_208_26.py

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#
2+
# @lc app=leetcode.cn id=208 lang=python
3+
#
4+
# [208] 实现 Trie (前缀树)
5+
#
6+
# https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/
7+
#
8+
# algorithms
9+
# Medium (58.88%)
10+
# Likes: 77
11+
# Dislikes: 0
12+
# Total Accepted: 8K
13+
# Total Submissions: 13.5K
14+
# Testcase Example: '["Trie","insert","search","search","startsWith","insert","search"]\n[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]'
15+
#
16+
# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
17+
#
18+
# 示例:
19+
#
20+
# Trie trie = new Trie();
21+
#
22+
# trie.insert("apple");
23+
# trie.search("apple"); // 返回 true
24+
# trie.search("app"); // 返回 false
25+
# trie.startsWith("app"); // 返回 true
26+
# trie.insert("app");
27+
# trie.search("app"); // 返回 true
28+
#
29+
# 说明:
30+
#
31+
#
32+
# 你可以假设所有的输入都是由小写字母 a-z 构成的。
33+
# 保证所有输入均为非空字符串。
34+
#
35+
#
36+
#
37+
38+
39+
class TireNode(object):
40+
def __init__(self):
41+
self.children = {}
42+
self.end = False
43+
44+
45+
class Trie(object):
46+
47+
def __init__(self):
48+
"""
49+
Initialize your data structure here.
50+
"""
51+
self.root = TireNode()
52+
53+
def insert(self, word):
54+
"""
55+
Inserts a word into the trie.
56+
:type word: str
57+
:rtype: None
58+
"""
59+
node = self.root
60+
for c in word:
61+
if c not in node.children:
62+
node.children[c] = TireNode()
63+
node = node.children[c]
64+
node.end = True
65+
66+
def search(self, word):
67+
"""
68+
Returns if the word is in the trie.
69+
:type word: str
70+
:rtype: bool
71+
"""
72+
node = self.root
73+
for c in word:
74+
if c not in node.children:
75+
return False
76+
node = node.children[c]
77+
return node.end
78+
79+
def startsWith(self, prefix):
80+
"""
81+
Returns if there is any word in the trie that starts with the given prefix.
82+
:type prefix: str
83+
:rtype: bool
84+
"""
85+
node = self.root
86+
for c in prefix:
87+
if c not in node.children:
88+
return False
89+
node = node.children[c]
90+
return True
91+
92+
93+
# Your Trie object will be instantiated and called as such:
94+
# trie = Trie()
95+
# print(trie.insert("apple"))
96+
# print(trie.search("apple"))
97+
# print(trie.search("app"))
98+
# print(trie.startsWith("app"))
99+
# print(trie.insert("app"))
100+
# print(trie.search("app"))
101+

Week_04/id_26/LeetCode_211_26.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#
2+
# @lc app=leetcode.cn id=211 lang=python
3+
#
4+
# [211] 添加与搜索单词 - 数据结构设计
5+
#
6+
# https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/description/
7+
#
8+
# algorithms
9+
# Medium (38.92%)
10+
# Likes: 51
11+
# Dislikes: 0
12+
# Total Accepted: 2.8K
13+
# Total Submissions: 7.3K
14+
# Testcase Example: '["WordDictionary","addWord","addWord","addWord","search","search","search","search"]\n[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]'
15+
#
16+
# 设计一个支持以下两种操作的数据结构:
17+
#
18+
# void addWord(word)
19+
# bool search(word)
20+
#
21+
#
22+
# search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
23+
#
24+
# 示例:
25+
#
26+
# addWord("bad")
27+
# addWord("dad")
28+
# addWord("mad")
29+
# search("pad") -> false
30+
# search("bad") -> true
31+
# search(".ad") -> true
32+
# search("b..") -> true
33+
#
34+
#
35+
# 说明:
36+
#
37+
# 你可以假设所有单词都是由小写字母 a-z 组成的。
38+
#
39+
#
40+
41+
42+
class TrieNode(object):
43+
def __init__(self):
44+
self.children = {}
45+
self.end = False
46+
47+
48+
class WordDictionary(object):
49+
50+
def __init__(self):
51+
"""
52+
Initialize your data structure here.
53+
"""
54+
self.root = TrieNode()
55+
56+
def addWord(self, word):
57+
"""
58+
Adds a word into the data structure.
59+
:type word: str
60+
:rtype: None
61+
"""
62+
node = self.root
63+
for c in word:
64+
if c not in node.children:
65+
node.children[c] = TrieNode()
66+
node = node.children[c]
67+
node.end = True
68+
69+
def search(self, word):
70+
"""
71+
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
72+
:type word: str
73+
:rtype: bool
74+
"""
75+
self.ans = False
76+
self._match(self.root, word)
77+
return self.ans
78+
79+
def _match(self, root, word):
80+
if not word:
81+
if root.end:
82+
self.ans = root.end
83+
return
84+
if word[0] == '.':
85+
for node in root.children.values():
86+
self._match(node, word[1:])
87+
if word[0] not in root.children:
88+
return
89+
self._match(root.children[word[0]], word[1:])

Week_04/id_26/LeetCode_240_26.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#
2+
# @lc app=leetcode.cn id=240 lang=python
3+
#
4+
# [240] 搜索二维矩阵 II
5+
#
6+
# https://leetcode-cn.com/problems/search-a-2d-matrix-ii/description/
7+
#
8+
# algorithms
9+
# Medium (36.82%)
10+
# Likes: 111
11+
# Dislikes: 0
12+
# Total Accepted: 17.8K
13+
# Total Submissions: 48.2K
14+
# Testcase Example: '[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]\n5'
15+
#
16+
# 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
17+
#
18+
#
19+
# 每行的元素从左到右升序排列。
20+
# 每列的元素从上到下升序排列。
21+
#
22+
#
23+
# 示例:
24+
#
25+
# 现有矩阵 matrix 如下:
26+
#
27+
# [
28+
# ⁠ [1, 4, 7, 11, 15],
29+
# ⁠ [2, 5, 8, 12, 19],
30+
# ⁠ [3, 6, 9, 16, 22],
31+
# ⁠ [10, 13, 14, 17, 24],
32+
# ⁠ [18, 21, 23, 26, 30]
33+
# ]
34+
#
35+
#
36+
# 给定 target = 5,返回 true。
37+
#
38+
# 给定 target = 20,返回 false。
39+
#
40+
#
41+
42+
43+
class Solution(object):
44+
def searchMatrix(self, matrix, target):
45+
"""
46+
:type matrix: List[List[int]]
47+
:type target: int
48+
:rtype: bool
49+
思路:从左下角开始,相等直接返回
50+
若大于目标值,则不可能在这一列,指针向左
51+
若小于目标值,则不可能在这一排,指针向上
52+
时间复杂度O(m+n)
53+
"""
54+
if not matrix or not matrix[0]:
55+
return False
56+
m, n = len(matrix)-1, 0
57+
58+
while m >= 0 and n < len(matrix[0]):
59+
if matrix[m][n] == target:
60+
return True
61+
if matrix[m][n] < target:
62+
n += 1
63+
else:
64+
m -= 1
65+
return False
66+
67+
68+
# print(Solution().searchMatrix([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [
69+
# 3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 333))

Week_04/id_26/LeetCode_46_26.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#
2+
# @lc app=leetcode.cn id=46 lang=python
3+
#
4+
# [46] 全排列
5+
#
6+
# https://leetcode-cn.com/problems/permutations/description/
7+
#
8+
# algorithms
9+
# Medium (69.33%)
10+
# Likes: 291
11+
# Dislikes: 0
12+
# Total Accepted: 28.6K
13+
# Total Submissions: 41.1K
14+
# Testcase Example: '[1,2,3]'
15+
#
16+
# 给定一个没有重复数字的序列,返回其所有可能的全排列。
17+
#
18+
# 示例:
19+
#
20+
# 输入: [1,2,3]
21+
# 输出:
22+
# [
23+
# ⁠ [1,2,3],
24+
# ⁠ [1,3,2],
25+
# ⁠ [2,1,3],
26+
# ⁠ [2,3,1],
27+
# ⁠ [3,1,2],
28+
# ⁠ [3,2,1]
29+
# ]
30+
#
31+
#
32+
33+
34+
class Solution(object):
35+
def permute(self, nums):
36+
"""
37+
:type nums: List[int]
38+
:rtype: List[List[int]]
39+
时间复杂度:O(n^2)
40+
"""
41+
ans = []
42+
n = len(nums)
43+
44+
def helper(path=[], invited=set()):
45+
if len(path) == n:
46+
return ans.append(path)
47+
for j in nums:
48+
if j not in invited:
49+
invited.add(j)
50+
helper(path+[j], invited)
51+
invited.remove(j)
52+
53+
helper()
54+
return ans

0 commit comments

Comments
 (0)