daily coding problems

Problem #1 [Easy]

问题描述:

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

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 at i.

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值