您的位置:首页 > 其它

LeetCode_1---Two Sum

2015-05-28 13:51 411 查看
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
翻译:给一个整形数组,找其中的两个数(题目好像并没有说明找其中几组)相加成为一个特殊的数即Target,index1 小于index2 ,数组从一开始。

代码如下:import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Test {
/*
* 别人代码:https://leetcode.com/discuss/34318/java-o-n-with-hash 时间复杂度为:O(n)
*
*
* 复杂度:O(n)+O(n),使用HashTable,Java的泛型应该多用。
*/

public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, ArrayList<Integer>> tempMap = new HashMap<>(numbers.length);
for (int i = 0; i < numbers.length; i++) {// 首先把代码存入HashTable
if (!tempMap.containsKey(numbers[i])) {
tempMap.put(numbers[i], new ArrayList<Integer>(2));
}
tempMap.get(numbers[i]).add(i);
}
System.out.println(tempMap);// test结果:{2=[0, 3], 11=[2], 7=[1]}
for (Integer key : tempMap.keySet()) {
if (key == target - key) {// 当出现两个数相同,且恰好之和为target的时候
if (tempMap.get(key).size() == 2) {// 未考虑出现多个相同的数的时候,只考虑了两个
result[0] = tempMap.get(key).get(0) + 1;// tempMap.get(key)的到的的是ArrayList
result[1] = tempMap.get(target - key).get(1) + 1;
}
return result;
}

if (tempMap.containsKey(target - key)) {
int a = tempMap.get(key).get(0), b = tempMap.get(target - key).get(0);
if (a < b) {
result[0] = a + 1;
result[1] = b + 1;
} else {
result[1] = a + 1;
result[0] = b + 1;
}
return result;
}
}
return null;
}

/*
* 最先想到的算法,时间复杂度为:O(n*n),空间复杂度O(1),运行通过,但是需要改进的应该很多,第一:可以考虑找出多组数据;第二:可以选择其他数据类型
* ,降低时间复杂度 (一般采取牺牲空间换取时间)
*/
public static int[] twoSum1(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = ++i;
result[1] = ++j;
return result;
}
}
}
return null;
}

public static void main(String[] args) {
int[] numbers = { 2, 7, 11, 2 };
int target = 4;
int[] result = twoSum(numbers, target);
System.out.println(result[0] + " --- " + result[1]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: