Difficult: Medium
Company: Google, Amazon
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer kis [-1e7, 1e7].
题目的意思很简单就是求一个数组里面 子数组(连续的元素)的和等于k的数目。
我一开始想到的方法就是很简单的,但是时间复杂度太长啦。
第一种方法就是:
res = 0
for i in range(len(nums)):
prefixSum = 0
for j in range(i, len(nums)):
prefixSum += nums[j]
if prefixSum == k:
res += 1
return res
空间复杂度和时间复杂度都是 o(n).
然后看到网上其他的方法。
dic = {0:1}
res = pre_sum = 0
for num in nums:
pre_sum += num
res += dic.get(pre_sum - k, 0)
dic[pre_sum] = dic.get(pre_sum, 0) + 1
return res
我发现有一系列的题目与这个题目很类似。并且是Google, Amazon很喜欢考的题目。我现在一一列出来。
2Sum
Two Sum II-input array is sorted
Two Sum III-Data structure design
Two Sum IV - input is a BST
3sum
3Sum Closest
3Sum Smaller
4sum
总结一下规律和解题思路。
1. Two Sum
Difficult: Easy
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
2. 3 Sum
Difficult: Medium
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c= 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
3. 4Sum
https://leetcode.com/problems/4sum/
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
4.Two Sum II - Input array is sorted
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.