您的位置:首页 > 其它

Two Sum

2015-07-09 19:32 162 查看
题目: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

如果使用暴力搜索,时间复杂度为O(n*n)

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] temp=new int[2];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
temp[0]=i+1;
temp[1]=j+1;
}
}
}
return temp;
}
}


解法:利用HashMap,存储数组中的值和Index,使用get方法,get到target-nums[i],

记录当前的index,否则将nums[i] put到HashMap中。时间复杂度只有O(n)。

public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //记录值和index
int[] ret = new int[2]; //辅助数组
for(int i=0; i<nums.length; i++){
if(map.get(target-nums[i]) != null){  //找到值对应的index
ret[0] = map.get(target-nums[i]) + 1;
ret[1] = i+1;
}else
map.put(nums[i], i);//没有找到则记录
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: