题目:https://leetcode.com/problems/two-sum/description/
问题描述:给定一个数组和任意两个数组中元素的和,要求返回数组中两个元素在数组中的位置
难度:简单
我自己的代码(C++):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int numsCount=nums.size();
vector<int> a;
for(int i=0;i<numsCount;i++)
{
for(int j=i+1;j<numsCount;j++)
{
if(nums[i]+nums[j]==target)
{
a.push_back(i);
a.push_back(j);
}
}
};
return a;
}
};
显然这样的实现方法,从性能上来说,没有什么明显的优势。
参考大佬的写法:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map={};
for i,val in enumerate(nums):
gap=target-val;
if gap in map:
return [map[gap],i]
else:
map[val]=i
return None
显然大佬的代码的时间复杂度O(n),空间复杂度O(n),性能更优。大佬采用的是map的查找功能,将我的代码中的循环嵌套修改为一次简单的循环+数据查找实现,而且从代码的严谨性来看,显然大佬考虑到了各种情况,而我只是简单得做到将功能实现。
进步的空间很大,加油!!!