leetcode -Two Sum
链接:https://leetcode.com/problems/two-sum/
题目内容:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
给出数组numbers 和数字target, 找出数组中两个元素之和为target的元素位置(数组的下标是1-based,即1为第一个元素)。
思路1:使用两层循环,判断满足numers[i]+numbers[j]==target的i和j 。这里时间复杂度是o(n^2)
思路2:使用HashMap,Map的key为numbers中的所有元素,value为元素对应的下标位置。遍历一次数组,如果numbers[i]+某数target,那么target-numbers[i]一定在数组中,即Map.get(某数)一定存在值,并且jMap.get(某数)。这样一次遍历就可以找到相对应的两个元素位置。
代码:
public int[] twoSum(int[] nums, int target) {
int index[] = new int[2];
int len = nums.length;
HashMap map = new HashMap<Integer, Integer>();
for (int i = 0; i < len; i++) {
map.put(nums[i], i + 1);
}
for (int i = 0; i < len; i++) {
index[0] = i + 1;
int val1 = nums[i];
int val2 = target - val1;
if (map.get(val2) != null) {
index[1] = (Integer) map.get(val2);
if(index[0]==index[1])
{
continue;
}
return index;
}
}
return index;
}