classSolution(object): deffirstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ if1notin nums: return1 iflen(nums) == 1: return2 for i inrange(len(nums)): if nums[i]<= 0or nums[i] > len(nums): nums[i] = 1 for i inrange(len(nums)): a = abs(nums[i]) if a == len(nums): nums[0] = -abs(nums[0]) else: nums[a] = -abs(nums[a]) for i inrange(1,len(nums)): if nums[i]>0: return i if nums[0] > 0: returnlen(nums) returnlen(nums)+1
classSolution(object): deftrap(self, height): """ :type height: List[int] :rtype: int """ l,r = 0,len(height)-1 water = 0 min_height = 0 while l < r: min_height = min(height[l],height[r]) while l < r and height[l] <= min_height: water += min_height - height[l] l += 1 while l < r and height[r] <= min_height: water += min_height - height[r] r -= 1 return water
classSolution(object): defjump(self, nums): """ :type nums: List[int] :rtype: int """ iflen(nums)<2: return0 cur = nums[0] pre = nums[0] res = 1 for i inrange(len(nums)): if cur < i: cur = pre res += 1 pre = max(pre,i + nums[i]) return res
另一份AC代码可能更好理解:
cur_far表示当前下一步可跳最远距离
cur_end表示上一跳所跳的位置
i表示当前所在的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defjump(self, nums): """ :type nums: List[int] :rtype: int """ cur_end, cur_farthest, step = 0, 0, 0 for i inrange(len(nums)-1): cur_farthest = max(cur_farthest, i+nums[i]) if cur_farthest >= len(nums) - 1: step += 1 return step if i == cur_end: cur_end = cur_farthest step += 1 return step
Very elegant method, but it took me a long time to understand. Some comment for the above:
e: longest distance in current minimum step
sc: minimum steps for reaching e
From i to e, even max is changed in a loop, it is reachable in one step.
思路三:动态规划
超级容易理解。 dp[i]代表的是到达index为i的位置的最少步数, 依然超时。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defjump(self, nums): """ :type nums: List[int] :rtype: int """ ifnot nums orlen(nums) == 0: return0 dp = [sys.maxsize] * len(nums) dp[0] = 0 for i inrange(1, len(nums)): for j inrange(i): if j + nums[j] >= i: dp[i] = min(dp[i], dp[j]+1) return dp[-1]