#2021/4/12
目录
爬楼梯
【题目】
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
【我的方法】
1)方法一:回溯,要么爬一个要么爬两个,结果超时了...
2)方法二:发现dp[n] = dp[n-1]+dp[n-2],然后用递归,结果还是超时了...
# 方法一
class Solution:
def climbStairs(self, n: int) -> int:
count = [0]
def backtrack(remain, current):
if current == n:
count[0] += 1
return
if current > n:
return
backtrack(remain - 1, current + 1)
backtrack(remain - 2, current + 2)
backtrack(n, 0)
return count[0]
# 方法二
class Solution:
def climbStairs(self, n: int) -> int:
if n==1:
return 1
elif n == 2:
return 2
else:
return self.climbStairs(n-1)+self.climbStairs(n-2)
【其他方法】
@面条 的评论:
第n个台阶只能从第n-1或者n-2个上来。到第n-1个台阶的走法 + 第n-2个台阶的走法 = 到第n个台阶的走法,已经知道了第1个和第2个台阶的走法,一路加上去。
# 借鉴该思路写出的代码
class Solution:
def climbStairs(self, n: int) -> int:
if n==1:
return 1
elif n == 2:
return 2
else:
i = 1
j = 2
k = 3
while(k<=n):
temp = i+j
i = j
j = temp
k += 1
return j
执行结果:
执行用时:40 ms, 在所有 Python3 提交中击败了58.38%的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了43.04%的用户
字符串中的第一个唯一字符
【题目】
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0s = "loveleetcode"
返回 2
提示:你可以假定该字符串只包含小写字母。
【我的方法】
用字典记录不同字符出现的次数,然后从头查找第一个出现次数仅一次的字符的下标。
class Solution:
def firstUniqChar(self, s: str) -> int:
s = list(s)
count = {}
for c in s:
if c in count:
count[c] += 1
else:
count[c] = 0
for i,c in enumerate(s):
if count[c] == 0:
return i
return -1
执行结果:
执行用时:160 ms, 在所有 Python3 提交中击败了30.82%的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了5.16%的用户
【其他方法】
@清风Python 的评论:
这道题使用HashMap算是比较高效的办法,分享两种解题思路。
解法1:
- 先使用collections.Counter()生成字典
- 然后在遍历字符串s
- 检索每个字符对应的字典value值是否为1
- 遇到1返回,未遇到最终返回-1
解法2:
- 创建一个字典d
- 然后循环遍历字符串
- 如字符不在d中,添加key值及对应下标,若存在更新value值为len(s) + 1
- 遍历完成后,查询字典value最小值小于length,直接返回,大于length返回-1。
# 方法一
class Solution:
def firstUniqChar(self, s: str) -> int:
d = Counter(s)
for i, j in enumerate(s):
if d[j] == 1:
return i
return -1
# 执行用时:100 ms, 在所有 Python3 提交中击败了81.73%的用户
# 内存消耗:15 MB, 在所有 Python3 提交中击败了76.27%的用户
# 方法二
class Solution:
def firstUniqChar(self, s: str) -> int:
d = {}
length = len(s)
for i in range(length):
if s[i] not in d:
d[s[i]] = i
else:
d[s[i]] = length + 1
ret = min(d.values())
return -1 if ret > length else ret
# 执行用时:128 ms, 在所有 Python3 提交中击败了56.40%的用户
# 内存消耗:15.1 MB, 在所有 Python3 提交中击败了22.76%的用户
*方法二的思路虽然和我的是一样的,但ta的判断方式很巧妙,用赋值length+1和min函数来判断。