Problem #1 [Easy]
问题描述:
Given a list of numbers and a number
k
, return whether any two numbers from the list add up tok
.For example, given
[10, 15, 3, 7]
andk
of17
, return true since10 + 7
is17
.Bonus: Can you do this in one pass?
思路1:
/*
用hash保存已经访问过的元素,hash访问元素和插入元素都是O(1),遍历每个元素时判断与之成和的元素是否存在。
时间复杂度O(n)
空间复杂度O(n)
*/
思路2:
/*
先排序 O(nlogn)
再用左右指针,滑动窗口 O(n)
时间复杂度O(nlogn)
空间复杂度 O(1)
*/
Problem #2 [Hard]
Given an array of integers, return a new array such that each element at index
i
of the new array is the product of all the numbers in the original array except the one ati
.For example, if our input was
[1, 2, 3, 4, 5]
, the expected output would be[120, 60, 40, 30, 24]
. If our input was[3, 2, 1]
, the expected output would be[2, 3, 6]
.Follow-up: what if you can't use division?
//思路1:对于当前的位置i,将位置i左边的元素乘积和右边的元素乘积分开计算,再相乘
//从左到右遍历,记录位置i左边的所有元素乘积 时间复杂度O(n),空间复杂度O(n)
//从右向左遍历,更新位置i的元素:乘右边所有元素的乘积,时间复杂度O(n),空间复杂度O(n)
vector<int> findProduct(vector<int> &arr){
int n = arr.size();
vector<int> res(n,1);
//从左向右遍历
for(int i=1;i<n;++i){
res[i] = res[i-1]*arr[i-1];
}
//从右向左遍历
int rP = arr[n-1];
for(int i=n-2;i>=0;--i){
res[i]*= rP;
rP*=arr[i];
}
return res;
}