# LeetCode # Two Sum

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int> ans;
for(int i=0;i<len-1;i++){
for(int j=i+1;j<len;j++)
if(nums[i]+nums[j]==target){
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
return ans;
}
};

solution.cpp: In member function twoSum
Line 14: Char 5: error: control reaches end of non-void function [-Werror=return-type]
}
^
cc1plus: some warnings being treated as errors

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int> ans;
for(int i=0;i<len-1;i++){
for(int j=i+1;j<len;j++)
if(nums[i]+nums[j]==target){
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
// 没有这一句    return ans;
}
};

so…如果有同样错误的小伙伴们你们知道该咋改了吧

class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++)
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
return null;
}
}

class Solution {
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 t = target-nums[i];
if(map.containsKey(t)&&map.get(t)!=i){
return new int[]{i,map.get(t)};
}
}
return null;
}
}