SuperMan - 1 year ago 94

Java Question

I felt like doing an algorithm and found this problem on leetcode

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

My solution is O(n^2). I wanted to know if there is better way of doing this? like O(n) or O(nlogn)

`import java.util.Arrays;`

public class ReturnIndex {

public int[] twoSum(int[] numbers, int target) {

int tail = numbers.length-1;

int[] n = new int[2];

for (int i=0;i<tail;i++) {

for(int j=i+1;j<tail;j++) {

if(target ==(numbers[i]+numbers[j])) {

n[0] = i+1;

n[1] = j+1;

}

}

}

return n;

}

public static void main(String[] args) {

int[] s = {150,24,79,50,88,345,3};

int value = 200;

ReturnIndex r = new ReturnIndex();

int[] a = r.twoSum(s,value);

System.out.println(Arrays.toString(a));

}

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

`O(n log n)`

time, `O(1)`

memory (not counting the list):

First, sort the list. This should take

`O(n log n)`

time, as most sort functions do.Iterate through the list, which should take

`O(n)`

time in the outer loop. At this point you can do a binary search for the closest matching integer in a sorted sublist, which should take`O(log n)`

time. This stage should wind up taking`O(n log n)`

total.

*Edit:* Check out Max's answer below. It's still O(n log n) time and O(1) memory, but he avoids the binary searches by walking a pointer from each end of the list.

`O(n)`

time, `O(n)`

memory:

Build a hash table, which should have `O(1)`

insertion and `O(1)`

contains. Then, in a `O(n)`

outer loop, for each number `i`

, check if `total - i`

is in the hash table. If not, add it; if so, then you've got your two numbers.

Either way, you would need an additional scan through the array to get the indices, but that's no problem--it only takes `O(n)`

time. If you wanted to avoid it you could keep the original index in the sorted list or hash table as needed, but that has a memory footprint instead of a time footprint.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**