去年未上传的代码,
问题描述
一个vector容器中,假定只有一个解,使得和为0,找出这两个数
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0;i<=nums.size()-2;i++)
{
for(int j = i+1;j <= nums.size()-1;j++)
{
if(nums[i]+nums[j] == target)
{
vector<int> list{i,j};
return list;
}
}
}
}
};
第一次解leetcode没经验,看了下playground,自己多虑了,输入在主函数已经完成,不需要在solution中做输入的功能,也符合面向对象的思想,只做接口封装,参数传入已经是打包好的package
int num;
while(cin>>num)
{
nums.push_back(num);
}
多余
个人认为,leetcode的把问题解决都封装成一个函数,不用考虑主函数的设计,而是关注算法,需要用的时候,调用接口即可,想深究输入输出格式,也可以在playground中查看,一般都比较标准
反思;另外循环变量也要注意,不能总是用i,j,因为误打,block在这里好久
advance:
对比map方法优化,使用hash Table,拿时间换空间
使用hash Table用key进行索引 ,lookup time 复杂度为O(n)
把原数组下标作为value,原本的具体数作为key
java代码
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}