首页 > 代码库 > leetcode_1_Two Sum

leetcode_1_Two Sum

描述:

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