您的位置:首页 > 其它

LeetCode------Two Sum

2015-07-06 13:06 337 查看
●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

●中文简要的意思是:给你一个整数的数组,和一个目标值,在数组中找到两个数字,使得这两个数字的加和等于目标值,输出这两个数字的位置坐标。

●解决这个问题的方法有很多,我最先想到的是试探法,即双层的循环,找到合适的就输出,代码如下:

public int[] twoSum(int[] nums, int target) {
int[] reslut = new int[2];
//试探法解决TwoSum
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
reslut[0]=i+1;
reslut[1]=j+1;
return reslut;
}
}
}
return reslut;
}


结果通过:Accepted

●还有另外一种方法,利用HashTable的存贮和查找元素的特性来解决这个问题,代码上只用了一层的循环,但其实资源的消耗上应该或高于第一种方式,因为用了集合数组,必不可少的增加了资源的消耗,且HashTable查找元素的操作底层也肯定是便利了全部的数组元素。

public int[] twoSum(int[] nums, int target) {
int[] reslut = new int[2];

Hashtable<Integer,Integer> list=new Hashtable<Integer,Integer>();

for(int i=0;i<nums.length;i++){
Integer n=list.get(nums[i]);
if(n==null){
list.put(nums[i],i);
}

n=list.get(target-nums[i]);
if(n!=null){
reslut[0]=i+1;
reslut[1]=n+1;
return reslut;
}
}
return reslut;
}


二者的效率上都不是很理想,希望读者有更好的解决方案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: