力扣LeetCode【每日一题】—— 面试题解答57 - II. 和为s的连续正数序列(Python3)滑动窗口
2020-03-08 16:04
573 查看
难度:简单 (LZ最近发现越是简单的题,解答方式越多)
类型:双指针、滑动窗口
题目:输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
[code]input:target = 9 output:[[2,3,4],[4,5]]
示例 2:
[code]input:target = 15 output:[[1,2,3,4,5],[4,5,6],[7,8]]
解法1:暴力法哈哈哈!第一反应还是暴力,是我太菜了
[code]class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: raw = list(range(1, ((target+1)//2 + 1))) # 建议转list,方便后续切片和append output = [] for i in range(len(raw)): for j in range(i + 1, len(raw)): if sum(raw[i: j+1]) == target: output.append(raw[i: j+1]) elif sum(raw[i: j+1]) < target: j += 1 else: break return output
解法2:滑动窗口(模拟双指针)
[code]class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: i, j, s = 1, 1, 0 # 滑动窗口的左、右边界及总和 output = [] while i <= target // 2: if s < target: s += j j += 1 # 右边界右移1 elif s > target: s -= i i += 1 # 左边界右移1 else: output.append(list(range(i, j))) s -= (2*i + 1) i += 2 # 左边界右移2格,移1格无解 return output
方法 |
提交结果 |
执行用时 |
内存消耗 |
语言 |
---|---|---|---|---|
1 | 通过 | 4400 ms | 15.1 MB |
Python3 |
2 | 通过 | 224 ms | 13.4 MB | Python3 |
更多解答可参考作者:quantumdriver 链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/xiang-jie-hua-dong-chuang-kou-fa-qiu-gen-fa-jian-g/
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【Golang】LeetCode-剑指Offer-面试题57 - II - 和为s的连续正数序列【两种解法】
- 面试题57-题目二:和为S的连续正数序列
- 【剑指offer】面试题57(2):和为S的连续正数序列
- 用python写leetcode【7】 --两个数组的交集 II(350)、递增的三元子序列(334)
- LeetCode--Longest Consecutive Sequence(最长连续序列)Python
- 利用python 完成 leetcode128 最长连续序列
- (剑指Offer)面试题41:和为s的连续正数序列
- 面试题41:和为s的两个数字VS和为s的连续正数序列
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- 用python写leetcode【16】 -- 最长连续序列(230)
- 面试题45:和为s的两个数字VS和为s的连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列
- 剑指offer之面试题41和为s的两个数字VS和为s的连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列
- 面试题40:输出和为指定值的连续正数序列
- 剑指offer面试题之和为S的连续正数序列
- 【网易面试题】和为n的连续正数序列
- 剑指offer面试题41_2 和为s的连续正数序列(java实现)
- 面试题41 和为S的连续正数序列
- [剑指offer][面试题41]和为s的两个数字 VS 和为s的连续正数序列