「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」
[除自身以外数组的乘积]
给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
示例:
输入: [1,2,3,4] 输出: [24,12,8,6]
提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶: 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
解题思路: 1.初始化ans=[] 2.遍历数组然后,将除第一个值意外的数据进行乘法处理 3.继续遍历,获取最终数据
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
ans =[1]
for i in range(1,len(nums)):
ans.append(ans[i-1]*nums[i-1])
k = 1
for i in range(len(nums)-1,-1,-1):
ans[i] = ans[i]*k
k*=nums[i]
return ans
执行结果:
[和为 K 的子数组]
给你一个整数数组 nums 和一个整数 k ,请你统计并返回该数组中和为 k 的连续子数组的个数。
示例 1:
输入:nums = [1,1,1], k = 2 输出:2
示例 2:
输入:nums = [1,2,3], k = 3 输出:2
提示:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
解题思路: 1.初始化count、index、res 2.遍历数组,通过前缀法进行计算是否符合条件。
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
count = {}
index =res = 0
for row in nums:
index += row
if index - k in count:
res += count[index - k]
if index == k:
res += 1
count[index] = count.get(index, 0) + 1
return res
执行结果: