leetcode #55 Jump Game
题目链接:https://leetcode.com/problems/jump-game/description/
题目描述:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
解题思路:
使用一个变量pow作为跳跃的动力,1个动力单位可以前进一格,则每次落在某个数组元素上时实际上等价于把动力补至最多该为数组元素大小的值,当动力为负时说明不能继续下去,说明无法抵达终点。
代码:
class Solution(object):
def canJump(self, nums):
pow = 0
for i in nums:
if pow < 0:
return False
if pow < i:
pow = i
pow = pow - 1
return True
通过情况:
![](https://i-blog.csdnimg.cn/blog_migrate/fb5588c95edacb162cefcebcf5429752.jpeg)
============================================================================
leetcode #66 Plus One
题目链接:https://leetcode.com/problems/plus-one/description/
题目描述:
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
解题思路:
从后往前遍历,遇到9则变为0,直到遇到非9的数,+1,结束遍历(另外判断一下是否遍历到了数组头部,是否需要在最前面+1)
代码:
class Solution(object):
def plusOne(self, digits):
for i in range(len(digits)-1,-1,-1):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
break
if digits[0] == 0:
digits.insert(0,1)
return digits
通过情况:
============================================================================
leetcode #338 Counting Bits
题目链接:https://leetcode.com/problems/counting-bits/description/
题目描述:
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
解题思路:
注意到递推公式:
当 2^n <= i < 2^(n+1)时
a[i] = a[i - 2^n] +1
共只需维护一个变量f,代表目前所处的2^n,且当i = 2*f - 1时更新f = 2*f即可
代码:
class Solution(object):
def countBits(self,num):
f = 1
a = []
for i in range(num + 1):
if i == 0:
a.append(0)
else:
a.append(a[i - f]+1)
if i == 2*f - 1:
f = 2*f
return a
通过情况: