The Sum of
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twoSum
should return indices of the numbers such that they add up to the target, where index1 mus T is less than INDEX2. Please note that your returned answers (both Index1 and Index2) is not zero-based.
Example
numbers= [2, 7, 11, 15]
, target=9
Return[1, 2]
Note
You may assume this each input would has exactly one solution
Challenge
Either of the following solutions is acceptable:
- O (n) Space, O (nlogn) time
- O (n) Space, O (n) time
public class Solution {
/*
* @param numbers:an array of integers
* @param target:target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, Index2 + 1] (Index1 < INDEX2)
*/
Public int[] Twosum (int[] numbers, int target) {
Write your code here
Int[] Result=new int[2];
if (Numbers==null | | numbers.length==0) return result;
int n=numbers.length;
for (int i=0;i<n;i++)
{
int left=n-1;
while (Left>i)
{
int Sum=numbers[i]+numbers[left];
if (sum==target)
{
result[0]=i+1;
result[1]=left+1;
return result;
}
Else
{
left--;
}
}
}
return result;
}
}
[Lintcode Medium] The sum of