1. Two Sum
- Total Accepted: 254411
- Total Submissions: 1031847
- Difficulty: Easy
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
思路:
1、暴力O(n2)
2、hash O(n): Hash表法,以空间换时间:时间复杂度:O(N)空间复杂度O(N).
更快的查找方法:hash表,给定一个数字,根据hash映射查找另一个数字是否在数组中,只需O(1)的时间,但需要承担O(N)的hash表存储空间。
代码1(暴力):
public class Solution {
public int[] twoSum(int[] nums, int target) {
int index[] = {-1,-1} ;
for(int i = 0 ; i < nums.length ; i++){
for(int j = 0 ; j < nums.length ; j++){
if(nums[j] == target - nums[i]){
index[0] = i;
index[1] = j;
break;
}
}
if(index[0] != -1 && index[1] != -1 && index[0] != index[1]) break;
}
return index;
}
}
Runtime: 58 ms
代码2(hash):
public class Solution {
public int[] twoSum(int[] numbers, int target) {
if (numbers != null) {
HashMap<Integer, Integer> num_map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (num_map.containsKey(numbers[i])) {
int index = num_map.get(numbers[i]);
int[] result = { index, i };
return result;
} else {
num_map.put(target - numbers[i], i);
}
}
}
return null;
}
}
Runtime:
6 ms
分析:
遍历传进来的数组int[] numbers,检查target - numbers[i]在不在hash表中,target - number[i]存储为hash表的key。如果在,就返回当前的i,和对应的key。