转系计算机的小白从今天起开始刷Leetcode!
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
方法一:暴力
第一题简单题,一开始就暴力,往后面搜索与第i个相加为target的数,复杂度是o(n2):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
int len = nums.size();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == target) {
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
执行用时 :180 ms, 在所有 cpp 提交中击败了48.55%的用户
内存消耗 :9.2 MB, 在所有 cpp 提交中击败了84.05%的用户
方法2:HashMap
然后用时太多辽,想想有啥办法,解答说可以用HashMap,于是修改思路如下:
遍历一遍所有元素,找(target减该元素)的位置是否为空,若为空则将(该元素下标)加入HashMap,否则将两个下标输出。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> hash;
vector<int> res(2,-1);
for(int i=0;i<nums.size();i++){
if(hash.find(target-nums[i]) != hash.end()){
res={hash[target-nums[i]],i};
return res;
}
else{
hash[nums[i]]=i;
}
}
return res;
};
};
执行用时 :12 ms, 在所有 cpp 提交中击败了91.04%的用户
内存消耗 :10.2 MB, 在所有 cpp 提交中击败了27.52%的用户
有用map的也有用unordered_map的,查了一下区别是map底层为红黑树,查找时间复杂度为logN,unordered_map底层是闭散列的哈希桶,查找为O(1)。试了一下unordered_map确实更快一些:
执行用时 :8 ms, 在所有 cpp 提交中击败了98.34%的用户
内存消耗 :10.1 MB, 在所有 cpp 提交中击败了38.85%的用户
思路是看了学的,但代码是自己打的,希望寒假能找个好实习555