子数组之和
题目地址
https://www.lintcode.com/problem/subarray-sum/my-submissions
描述
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
样例
样例 1:
输入: [-3, 1, 2, -3, 4]
输出: [0,2] 或 [1,3]
样例解释: 返回任意一段和为0的区间即可。
样例 2:
输入: [-3, 1, -4, 2, -3, 4]
输出: [1,5]
题解-前缀和
class Solution:
"""
@param nums: A list of integers
@return: A list of integers includes the index of the first number and the index of the last number
"""
def subarraySum(self, nums):
# write your code here
prefix_dict = {0: -1}
prefix_sum = 0
for index, value in enumerate(nums):
prefix_sum += value
if prefix_sum in prefix_dict:
return [prefix_dict.get(prefix_sum) + 1, index]
prefix_dict[prefix_sum] = index
return [-1, -1]
和为K的子数组
描述
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
输入:nums = [1,2,3], k = 3
输出:2
说明 :
数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarray-sum-equals-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
hash表
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
prefix_sum = {0: 1}
result = 0
curr = 0
for num in nums:
curr += num
if curr - k in prefix_sum:
result += prefix_sum[curr - k]
if curr in prefix_sum:
prefix_sum[curr] += 1
else:
prefix_sum[curr] = 1
return result
题解
代码更优雅的写法
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
prefix_sum = {0: 1}
result = 0
curr = 0
for num in nums:
curr += num
result += prefix_sum.get(curr - k, 0)
prefix_sum.setdefault(curr, 0)
prefix_sum[curr] += 1
return result
和为零的子矩阵
题目地址
https://www.lintcode.com/problem/submatrix-sum/description
描述
给定一个整数矩阵,请找出一个子矩阵,使得其数字之和等于0.输出答案时,请返回左上数字和右下数字的坐标。
如果有多个答案, 你可以返回其中任意一个.
样例
样例 1:
输入:
[
[1, 5, 7],
[3, 7, -8],
[4, -8 ,9]
]
输出: [[1, 1], [2, 2]]
样例 2:
输入:
[
[0, 1],
[1, 0]
]
输出: [[0, 0], [0, 0]]
题解-前缀和
class Solution:
"""
@param: matrix: an integer matrix
@return: the coordinate of the left-up and right-down number
"""
def submatrixSum(self, matrix):
# write your code here
if not matrix or not matrix[0]:
return None
row_length = len(matrix)
column_length = len(matrix[0])
for top in range(row_length):
arr = [0] * column_length
for down in range(top, row_length):
prefix_dict = {0: -1}
prefix_sum = 0
for column in range(column_length):
arr[column] += matrix[down][column]
prefix_sum += arr[column]
if prefix_sum in prefix_dict:
return [[top, prefix_dict[prefix_sum] + 1], [down, column]]
prefix_dict[prefix_sum] = column
标签:curr,nums,column,sum,prefix,数组
From: https://www.cnblogs.com/init0ne/p/14694831.html