# 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

• worsun
• 2015年09月19日 12:04
• 247

## 【LeetCode001算法/编程练习C++】--twoSum //从816ms到16ms的优化过程

LeetCode第一题
• zmdsjtu
• 2016年12月19日 10:21
• 341

## LeetCode_1_TwoSum_java

Two Sum Given an array of integers, return indices of the two numbers such that they add up to a sp...
• ac_li
• 2016年08月16日 22:08
• 102

## leetcode1 || TwoSum

Java中的Hashtable的用法：Java包含两个类，java.util.Hashtable 和java.util.HashMap，Hashtable和HashMap对象把一个key 和一个val...

## Leetcode 之 twoSum, ThreeSum, FourSum(K-Sum)问题

Leetcode之k sum 问题

## leetcode 1 TwoSum

leetcode 1. TwoSum问题描述： Given an array of integers, return indices of the two numbers such that th...

## leetcode:TwoSum

Leetcode 对于TwoSun题目的分析，以及用hashmap巧妙求解，代码为java实现

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