# leetcode算法之TwoSum

111人阅读 评论(0)

</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;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：16893次
• 积分：317
• 等级：
• 排名：千里之外
• 原创：13篇
• 转载：19篇
• 译文：0篇
• 评论：0条
评论排行