Skip to content

第四周作业#026 #217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions Week_04/id_26/LeetCode_169_26.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#
# @lc app=leetcode.cn id=169 lang=python
#
# [169] 求众数
#
# https://leetcode-cn.com/problems/majority-element/description/
#
# algorithms
# Easy (59.48%)
# Likes: 261
# Dislikes: 0
# Total Accepted: 49.3K
# Total Submissions: 82.6K
# Testcase Example: '[3,2,3]'
#
# 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
#
# 你可以假设数组是非空的,并且给定的数组总是存在众数。
#
# 示例 1:
#
# 输入: [3,2,3]
# 输出: 3
#
# 示例 2:
#
# 输入: [2,2,1,1,1,2,2]
# 输出: 2
#
#
#


class Solution(object):
def majorityElement1(self, nums):
"""
:type nums: List[int]
:rtype: int
解法1:排序
"""
nums.sort()
return nums[len(nums)//2]

def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
解法2: 递归+分治
分治问题模板步骤:
1.结束条件
2.拆分子问题
3.递归处理子问题
4.处理子问题的结果
"""
def helper(left, right):

if left == right:
return nums[left]

mid = (right+left) // 2

leftNum = helper(left, mid)
rightNum = helper(mid+1, right)

if leftNum == rightNum:
return leftNum
leftCount, rightCount = 0, 0
for i in range(left, right+1):
if nums[i] == leftNum:
leftCount += 1
elif nums[i] == rightNum:
rightCount += 1
return leftNum if leftCount >= rightCount else rightNum

return helper(0, len(nums)-1)


# print(Solution().majorityElement([1, 2, 1, 3, 1, 2, 1]))
101 changes: 101 additions & 0 deletions Week_04/id_26/LeetCode_208_26.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#
# @lc app=leetcode.cn id=208 lang=python
#
# [208] 实现 Trie (前缀树)
#
# https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/
#
# algorithms
# Medium (58.88%)
# Likes: 77
# Dislikes: 0
# Total Accepted: 8K
# Total Submissions: 13.5K
# Testcase Example: '["Trie","insert","search","search","startsWith","insert","search"]\n[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]'
#
# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
#
# 示例:
#
# Trie trie = new Trie();
#
# trie.insert("apple");
# trie.search("apple"); // 返回 true
# trie.search("app"); // 返回 false
# trie.startsWith("app"); // 返回 true
# trie.insert("app");
# trie.search("app"); // 返回 true
#
# 说明:
#
#
# 你可以假设所有的输入都是由小写字母 a-z 构成的。
# 保证所有输入均为非空字符串。
#
#
#


class TireNode(object):
def __init__(self):
self.children = {}
self.end = False


class Trie(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TireNode()

def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TireNode()
node = node.children[c]
node.end = True

def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for c in word:
if c not in node.children:
return False
node = node.children[c]
return node.end

def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True


# Your Trie object will be instantiated and called as such:
# trie = Trie()
# print(trie.insert("apple"))
# print(trie.search("apple"))
# print(trie.search("app"))
# print(trie.startsWith("app"))
# print(trie.insert("app"))
# print(trie.search("app"))

89 changes: 89 additions & 0 deletions Week_04/id_26/LeetCode_211_26.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#
# @lc app=leetcode.cn id=211 lang=python
#
# [211] 添加与搜索单词 - 数据结构设计
#
# https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/description/
#
# algorithms
# Medium (38.92%)
# Likes: 51
# Dislikes: 0
# Total Accepted: 2.8K
# Total Submissions: 7.3K
# Testcase Example: '["WordDictionary","addWord","addWord","addWord","search","search","search","search"]\n[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]'
#
# 设计一个支持以下两种操作的数据结构:
#
# void addWord(word)
# bool search(word)
#
#
# search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
#
# 示例:
#
# addWord("bad")
# addWord("dad")
# addWord("mad")
# search("pad") -> false
# search("bad") -> true
# search(".ad") -> true
# search("b..") -> true
#
#
# 说明:
#
# 你可以假设所有单词都是由小写字母 a-z 组成的。
#
#


class TrieNode(object):
def __init__(self):
self.children = {}
self.end = False


class WordDictionary(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()

def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.end = True

def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
self.ans = False
self._match(self.root, word)
return self.ans

def _match(self, root, word):
if not word:
if root.end:
self.ans = root.end
return
if word[0] == '.':
for node in root.children.values():
self._match(node, word[1:])
if word[0] not in root.children:
return
self._match(root.children[word[0]], word[1:])
69 changes: 69 additions & 0 deletions Week_04/id_26/LeetCode_240_26.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#
# @lc app=leetcode.cn id=240 lang=python
#
# [240] 搜索二维矩阵 II
#
# https://leetcode-cn.com/problems/search-a-2d-matrix-ii/description/
#
# algorithms
# Medium (36.82%)
# Likes: 111
# Dislikes: 0
# Total Accepted: 17.8K
# Total Submissions: 48.2K
# 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'
#
# 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
#
#
# 每行的元素从左到右升序排列。
# 每列的元素从上到下升序排列。
#
#
# 示例:
#
# 现有矩阵 matrix 如下:
#
# [
# ⁠ [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]
# ]
#
#
# 给定 target = 5,返回 true。
#
# 给定 target = 20,返回 false。
#
#


class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
思路:从左下角开始,相等直接返回
若大于目标值,则不可能在这一列,指针向左
若小于目标值,则不可能在这一排,指针向上
时间复杂度O(m+n)
"""
if not matrix or not matrix[0]:
return False
m, n = len(matrix)-1, 0

while m >= 0 and n < len(matrix[0]):
if matrix[m][n] == target:
return True
if matrix[m][n] < target:
n += 1
else:
m -= 1
return False


# print(Solution().searchMatrix([[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]], 333))
54 changes: 54 additions & 0 deletions Week_04/id_26/LeetCode_46_26.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#
# @lc app=leetcode.cn id=46 lang=python
#
# [46] 全排列
#
# https://leetcode-cn.com/problems/permutations/description/
#
# algorithms
# Medium (69.33%)
# Likes: 291
# Dislikes: 0
# Total Accepted: 28.6K
# Total Submissions: 41.1K
# Testcase Example: '[1,2,3]'
#
# 给定一个没有重复数字的序列,返回其所有可能的全排列。
#
# 示例:
#
# 输入: [1,2,3]
# 输出:
# [
# ⁠ [1,2,3],
# ⁠ [1,3,2],
# ⁠ [2,1,3],
# ⁠ [2,3,1],
# ⁠ [3,1,2],
# ⁠ [3,2,1]
# ]
#
#


class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
时间复杂度:O(n^2)
"""
ans = []
n = len(nums)

def helper(path=[], invited=set()):
if len(path) == n:
return ans.append(path)
for j in nums:
if j not in invited:
invited.add(j)
helper(path+[j], invited)
invited.remove(j)

helper()
return ans
Loading