# leetcode算法之TwoSum

</pre><strong>Two Sum</strong><p>Given an array of integers, find two numbers such that they add up to a specific target number.</p><p>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.</p><p>You may assume that each input would have exactly one solution.</p><p style="font-family:monospace"><strong>Input:</strong> numbers={2, 7, 11, 15}, target=9<strong>Output:</strong> index1=1, index2=2</p><p style="font-family:monospace"></p><p style="font-family:monospace"><pre name="code" class="java"> public int[] twoSum(int[] nums, int target) {
int arr[]=new int[2];
for(int i=0;i<nums.length-1;i++)
{
for(int j=i+1;j<nums.length;j++)
{
if(nums[i]+nums[j]==target)
{
arr[0]=i+1;
arr[1]=j+1;
return arr;
}
}
}
return null;
}

 public int[] twoSum(int[] numbers, int target) {
// TODO Auto-generated method stub
int index1 = 0, index2 = 0, n = numbers.length;

HashMap<Integer, Integer> hashmap=new HashMap<Integer, Integer>();
for(int i=0;i<n;i++)
{
hashmap.put(numbers[i], i);
}

for (int i = 0; i < n; i++) {
int m = target - numbers[i];
Integer j=hashmap.get(m);
boolean b =(hashmap.containsKey(m))&&(j.intValue()!=i);
if (b) {
//
index1=i+1;
index2=j+1;
break;
}
}
int[] a={index1,index2};
return a;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode算法之TwoSum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)