您的位置:首页 > 编程语言 > Java开发

LeetCode java Two Sum

2015-04-02 06:21 316 查看
The Problem:

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

How to solve it:

First, copy the original array into a new array, then sorted the new array. Then find the two number we need in the new array, then find their corresponding index in the original array.

Time complexity is O(nlogn) +O(n) +O(n) = O(nlogn)

Space complexity is O(n).

Code:

public class Solution {
public int[] twoSum(int[] numbers, int target) {
int N = numbers.length;
int[] sorted = new int
;//build a new array
System.arraycopy(numbers, 0, sorted, 0, N);//copy the old array to the new one
Arrays.sort(sorted);//sort it
//find the two numbers using the sorted arrays
int first = 0;//two pointer. One from the beginning of the array,one from the end of the array
int second = sorted.length - 1;
while(first < second){
if(sorted[first] + sorted[second] < target){
first++;
continue;
}
else if(sorted[first] + sorted[second] > target){
second--;
continue;
}
else break;
}
int number1 = sorted[first];
int number2 = sorted[second];
//Find the two indexes in the original array
int index1 = -1, index2 = -1;
for(int i = 0; i < N; i++){
if((numbers[i] == number1) || (numbers[i] == number2)){
if(index1 == -1)
index1 = i + 1;
else
index2 = i + 1;
}

}
int [] result = new int[]{index1, index2};
Arrays.sort(result);
return result;
}
}


There is another way to solve this by using hashmap, which has O(n) complexity. In fact there is no difference than brute force, is just that the searching speed of hashmap is O(1).

public int[] twoSum(int[] numbers, int target) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int n = numbers.length;
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++)
{
if (map.containsKey(target - numbers[i]))
{
result[0] = map.get(target-numbers[i]) + 1;
result[1] = i + 1;
break;
}
else
{
map.put(numbers[i], i);
}
}
return result;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: