码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_1_Two Sum

时间:2015-01-27 20:24:52      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:leetcode   two sum   hashset   

描述:

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

标签:leetcode   two sum   hashset   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!