高级编程技术,第八周

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

通过情况:



============================================================================

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

通过情况:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值