【leetcode 01】 two sum 两数之和

Problem decription:

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:

1
2
3
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目描述:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

1
2
3
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

Solution:

  • 排序数组,用两个头尾指针遍历即可,排序复杂度为O(nlogn),空间复杂度为O(1);
  • 利用map,以<值,数组下标>方式储存,再遍历数组即可;

    这里采用第二种解法,要注意考虑数组中包含重复值的情况,在加入map的过程中要做判断;

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.HashMap;
class {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> h=new HashMap<Integer,Integer>();
int []result=new int[2];
boolean flag=true;
for(int i=0;i<nums.length;i++){
if(h.containsKey(nums[i]) && 2*nums[i]==target){
result[0]=h.get(nums[i]);
result[1]=i;
flag=false;
}
h.put(nums[i],i);

}
for(int j=0;j<nums.length;j++){
if(h.containsKey(target-nums[j]) && target-nums[j]!=nums[j] && flag){
result[0]=j;
result[1]=h.get(target-nums[j]);
break;
}

}

return result;
}
}