您的位置:首页 > 其它

leetcode 之 Two Sum 解题思路

2014-07-06 20:50 363 查看
题目如下;

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相等。时间复杂度O(n*n),系统报超时

改进:

采用hashmap,将数组中的每一个值作为key, 该值所在的下标作为value,存入hashmap中。但会存在一个问题,相同的key,在hashmap中只会存在一份。但是数组中可能有多个相同的值。此时可以采用LinkedList存储所有有相同key的下标集合。比如数组numbers={2,3,2,1,2},当key为2时,value={1,3,5};key为3时,value={2};key为1时,value={4}。

下面给出具体的步骤:

遍历numbers:

   1)取出 numbers(i),取名为one

   2)用target-one,取名为two

   3)判断one和two是否都在hashmap中,如果都在执行4),否则继续循环

   4)根据one值取出hashmap中的value,为list,从list中取出头结点,并且删除头节点,得到头结点的值为index1。

       根据two值取出hashmap中的value,为list,判断list是否为空,不为空,则删除头节点,得到头节点的值为index2,停止循环。//这里判断list是否为空,防止one,two取出相同的list,但是list中只存在一个值得情况。

       list为空,继续循环

代码如下:

public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] twoIndex = new int[2];

Map<Integer, LinkedList<Integer>> map = new HashMap<Integer, LinkedList<Integer>>();
for(int i = 0; i < numbers.length; i++){
if(!map.containsKey(numbers[i])){
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(i + 1);
map.put(numbers[i], list);
}else{
LinkedList<Integer> list = map.get(numbers[i]);
list.add(i + 1);
map.put(numbers[i], list);
}
}

for(int i = 0; i < numbers.length; i++){
int one = numbers[i];
int two = target - one;
if(map.containsKey(one) && map.containsKey(two)){
LinkedList<Integer> list = map.get(one);
twoIndex[0] = list.remove();
list = map.get(two);
if(list.size() > 0){
twoIndex[1] = list.remove();
break;
}
}
}
return twoIndex;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode two sum