1 Two Sum

Two Sum

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

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");
}

public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：1 Two Sum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)