力扣算法·简单(1)
1.两数之和
第一想到的就是暴力解法了,2重for循环解决
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i=0,j=1;
vector<int> result={
i,j};
for(i=0;i<nums.size()-1;i++){
for(j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
result={
i,j};
return result;
}
}
}
return result;
}
};
发现官方还有更好的方法,是有哈希表做的,学习一哈
java:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{
hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com