Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
第一种实现:
public static int[] twoSum(int[] nums, int target) {
int[] results = new int[2];
for (int i = 0; i < nums.length; i++) {
results[0] = nums[i];
results[1] = target - results[0];
for (int j = nums.length - 1; j >= 0; j--) {
if ((nums[j] == results[1]) && (i != j)) {
results[0] = i;
results[1] = j;
return results;
}
}
}
return null;
}
第二种实现:
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> dict = new HashMap<>();
int[] results = new int[2];
int another;
for (int i = 0; i < nums.length; i++) {
another = target - nums[i];
if (dict.containsKey(another)) {
results[0] = dict.get(another);
results[1] = i;
return results;
}
dict.put(nums[i], i);
}
return results;
}
C++版本只给出第二种实现,使用了STL中的unordered_map
结构。
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> dict;
vector<int> results = vector<int>(2);
int another;
for (int i = 0; i < nums.size(); i ++)
{
another = target - nums[i];
if (dict.find(another) != dict.end())
{
results[0] = dict[another];
results[1] = i;
return results;
}
dict[nums[i]] = i;
}
return results;
}