首页 > 其他 > 详细

leetcode_1_Two Sum

时间:2015-01-27 20:22:41      阅读:179      评论:0      收藏:0      [点我收藏+]

描述:

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

思路:

思路很简单,将所有的元素放入HashSet中,如果target-Numbers[i]在hashSet中,且Numbers[i]不等于target-Numbers[i]中,满足条件,将Numbers[i]和target-Numbers[i]的index放在数组里返回即可。

代码:

public int[] twoSum(int[] numbers, int target) {
        int []result=new int[2];
        HashSet<Integer>hp=new HashSet<Integer>();
        int i=0,len=numbers.length-1;
        for(int num:numbers)
        	hp.add(num);
        boolean flag=false;
        while(i<len)
        {
        	flag=hp.contains(target-numbers[i]);
        	if(flag)
        	{
        		result[0]=i+1;
                for(int j=i;j<=len;j++)
                	if(target-numbers[i]==numbers[j])
                		result[1]=j+1;
                if(result[0]==result[1])
                {
                	flag=false;
                	i++;
                	continue;
                }
                else
					break;
        	}
        	i++;
        }
        return result;
    }

结果:

技术分享

leetcode_1_Two Sum

原文:http://blog.csdn.net/mnmlist/article/details/43198455

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!