DATAwhale编程第六期任务二
数组
实现一个支持动态扩容的数组
实现一个大小固定的有序数组,支持动态增删改操作
实现两个有序数组合并为一个有序数组
学习哈希表思想,并完成leetcode上的两数之和(1)及Happy Number(202)!(要求全部用哈希思想实现!)
字符串
实现一个字符集,只包含 a~z 这 26 个英文字母的 Trie 树
实现朴素的字符串匹配算法
对应的 LeetCode 练习题
数组
Three Sum(求三数之和)
英文版:https://leetcode.com/problems/3sum/
中文版:https://leetcode-cn.com/problems/3sum/
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
result,visited=set(),{}
for i in xrange(len(nums)-2):
table,target={},-nums[i]
if nums[i] not in visited:
for j in xrange (i+1,len(nums)):
if nums[j] not in table:
table[target-nums[j]]=nums[j]
else:
result.add((nums[i],target-nums[j],nums[j]))
visited[nums[i]]=1
return list(result)
Majority Element(求众数)
英文版:https://leetcode.com/problems/majority-element/
中文版:https://leetcode-cn.com/problems/majority-element/
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic={}
for num in nums:
if num not in dic:
dic[num]=1
if dic[num]>len(nums)//2:
return num
else:
dic[num]+=1
Missing Positive(求缺失的第一个正数)
英文版:https://leetcode.com/problems/first-missing-positive/
中文版:https://leetcode-cn.com/problems/first-missing-positive/
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
result=1
for num in nums:
if num == result:
result += 1
return result
字符串
Reverse String (反转字符串)
英文版:https://leetcode.com/problems/reverse-string/
中文版:https://leetcode-cn.com/problems/reverse-string/
#法一
class Solution(object):
def reverseString(self, s):
n=len(s)
i,j=0,n-1
while i<j:
s[i],s[j]=s[j],s[i]
i+=1
j-=1
return s
#法二
class Solution(object):
def reverseString(self, s):
n=len(s)
for i in range(n/2):
s[i],s[n-1-i]=s[n-i-1],s[i]
return s
Reverse Words in a String(翻转字符串里的单词)
英文版:https://leetcode.com/problems/reverse-words-in-a-string/
中文版:https://leetcode-cn.com/problems/reverse-words-in-a-string/
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return " ".join(s.strip().split()[::-1])
String to Integer (atoi)(字符串转换整数 (atoi))
英文版:https://leetcode.com/problems/string-to-integer-atoi/
中文版:https://leetcode-cn.com/problems/string-to-integer-atoi/
import sys
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str)==0:
return 0
else:
l=list(str.strip())
n=len(l)
if n>0:
sig=-1 if l[0]=='-' else 1
if l[0] in ['-','+'] : del l[0]
res,i=0,0
while i < len(l) and l[i].isdigit():
res=res*10 + ord(l[i])-ord('0')
i+=1
return max(-2**31,min(sig*res,2**31-1))
else:
return 0