leedcode做题总结,题目Two Sum2011-03-13

这是leedcode里最老的一道题,知道两数的和然后从一个无序的int数组中找到这两个数。一开始用两层for暴力查找果断超时了。然后修改了一下,打算排序后用二分查找第二个加数,但是要对数组进行排序,记录下每个元素的位置,也很麻烦。于是我就想到了HashMap进行查找。


使用HashMap进行查找

Map中 KEY为数组元素值,VALUE为index,这样可以迅速查找到某一元素值是否存在,和找到对应的index。代码如下:


public static int[] twoSum2(int[] numbers, int target) {

        HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
        int[] res={-1,-1};
        int num = numbers.length;
        for(int i=0;i<num;i++){
            mp.put(numbers[i],i);
        }
        for(int j=0;j<num;j++){
            int ser = target-numbers[j];
            if(mp.containsKey(ser)){
                res[0]=j+1;
                res[1]=mp.get(ser)+1;
                if(res[0]==res[j]||res[0]>res[j]) continue;
                return res;
            }
        }
        return res;
    }


Update 2015/07/22: 这次做的是历遍keySet,但是这样不如历遍原数组方便,历遍原数组可以保证顺序,不许判断两个index大小和是否有重复


public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int [] res = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i=0; i<nums.length; i++){
            if (map.containsKey(nums[i]) && nums[i]*2 == target){
                res[0] = map.get(nums[i]);
                res[1] = i+1;
                return res;
            }
            map.put(nums[i], i+1);
        }
        for (int key: map.keySet()){
            if (map.containsKey(target - key)){
                if(map.get(key) < map.get(target - key)){
                    res[0] = map.get(key);
                    res[1] = map.get(target - key);
                }else{
                    res[1] = map.get(key);
                    res[0] = map.get(target - key);
                }
            }
        }
             
        
        return res;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值