leetcode 之 Two Sum 解题思路

题目如下;

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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值