刷题3
来源:互联网 发布:数据库except 编辑:程序博客网 时间:2024/06/15 17:05
1题目描述:
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
只能在原地操作,不能添加新内存。
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ k = k%len(nums) nums[:] = nums[-k:]+nums[:-k]
值得注意的是,刚开始用nums = nums[-k:] + nums[:-k],结果不对!!!这个细节还得研究。
2题目描述:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
设置暂时最大值与最大值,实时比较大小。时间复杂度O(n)
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 curSum = maxSum = nums[0] for num in nums[1:]: curSum = max(num, curSum + num) maxSum = max(maxSum, curSum) return maxSum
阅读全文
0 0
- 刷题3
- [刷题]3 Sum
- 剑指Offer刷题(3)
- Leetcode 刷题: 3Sum
- LeetCode刷题(3)
- Leetcode刷题(3)
- LeetCode刷题(3)
- leetcode刷题-堆栈3
- Leetcode 刷题: 3Sum Closest
- 刷题
- 刷题
- 刷题
- 刷题
- 刷题
- 刷题。。。
- 刷题
- 刷题
- 刷题
- java-ApiDemo
- office 2010/2013激活工具及VS2013密钥
- Yii2 Lesson
- 转载-好用的linux软件合集
- android studio- java注释自己动手弄起来
- 刷题3
- JAVA中多态的“缺陷”
- java-ApiValueDemo
- java-SimpleDateFormatDemo & BirthDemo
- java-TransDemo
- 序列化对象为xml文件,将xml文件反序列化为对象
- 关于python ide
- 转载-android studio 各种问题
- [置顶]总结汇总