LeetCode TwoSum 找到两个数字之和

这题是说存在一个整数数组,要求找到两个数字相加之后可以和目标整数相等。题目里面存在一个问题就是这个数组是无序的,另外就是这个数组中可能存在两个相等的数字,要求我们返回这个数在数组中对应的位置,提示这个就是说要对index加1之后才是位置。
解法1:将这个数组排序,由于题目收欧诺个说过

each input would have exactly one solution.也就是说有的话就只可能有一个解法,所以我们可以先对数组排序然后定义两个指针寻找既可。但是这个时间复杂度有O(nlogn)
解法2:推荐解法,我们想到的是将这个数组首先存入HashMap中,利用HashMap搜索数据时间复杂度为1的特性查找数据,思路是做一次for循环,每次都把本次的数据放入hashmap,然后寻找是否存在满足条件的一对数。注意存放时如下所示Map<数值,索引值>。

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Cookies on 2015-01-04.
 * 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
 */
public class TwoSum {
    public static void main(String[] args){
        int[] values = new int[3];

        values[0] = 3;
        values[1] = 3;
        values[2] = 4;

        int[] result = twoSum(values,6);
        System.out.print("0:"+result[0]+"1:"+result[1]);
    }

    public static int[] twoSum(int[] numbers,int target){
        if(numbers==null || numbers.length<2) return null;

        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<numbers.length;i++){
            if(map.get(numbers[i])==null){
                map.put(numbers[i],i);
            }
            int temp = target-numbers[i];
            if (map.get(temp)!=null && map.get(temp)!=i){
                int a = map.get(temp);
                int[] values = new int[2];
                values[0] = a;
                values[1] = i;
                return values;
            }
        }
        return null;
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值