Two Sum(两个数字和)

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

解题思路
方法1、将每个值存到Map中个,其中key为值,value为其下标;遍历一下所有的数值x,查找target与x的差判断其是否在map中存在,存在则可以直接找到两个的下标。
因为map不能存储两个相同的数值,但数据可能存在有两个数值重复需要对map的value进行处理,将其存成字符串,后面再进行解析。因为map查找数据的复杂度为O(logn),所以整体的时间复杂度为O(nlogn)
方法2、当数据的数值不大的时候可以考虑定义一个大的数组,用空间换时间,即数组flagNum[i]=0,将数值的对应的数组的下标置为1,有多个就进行累加,这样查找的时间复杂度为O(1),整体的时间复杂度为O(n)

public int[] twoSum(int[] nums, int target) {
        int result[] = new int[2];
        int i = 0;
        Map<Integer,String> numMap = new HashMap<Integer,String>();
        for(i  = 0; i < nums.length; i++){
            if (!numMap.containsKey(nums[i])) {
                numMap.put(nums[i], i+"");
            }else{
                String t = numMap.get(nums[i]);
                numMap.put(nums[i], t+","+i);//该值有多个
            }
        }
        Iterator its = numMap.entrySet().iterator();
        while(its.hasNext()){
            Map.Entry<Integer,String> entry = (Entry<Integer, String>) its.next();
            int num = entry.getKey();
            String indexStr[] = entry.getValue().split(",");
            int distNum = target - num;
            result[0] = Integer.parseInt(indexStr[0]);
            if (distNum == num) {//判断是否有其他的该数字
                if(indexStr.length > 1 ){
                    result[1] = Integer.parseInt(indexStr[1]);
                    break;
                }
            }else{
                if (numMap.containsKey(distNum)) {
                    result[1] = Integer.parseInt(numMap.get(distNum));
                    break;
                }               
            }   
        }

//        System.out.println(result[0]+" "+result[1]);

        return result;
    }

目前研究于Spark与Hadoop,群QQ号:521066396(spark,hadoop交流群),欢迎加入共同学习,一起进步~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值