LeetCode专栏L001_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, and you may not use the same element twice.

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

中文大意:
输入数组,以及一个target值,如果num[i]+num[j]=target,并且i!=j,则返回i,j。

解题思路:
1.暴力。复杂度O(n^2),超时。
2.hash。用哈希表存储target-num[i]作为key值,i为value值。取num[i],返回的i即为对应的j值。复杂度O(n)。
3.先排序,后左右夹逼。排序O(nlogn),夹逼O(n),最终O(nlogn)。但是排序会影响原来的数组顺序,对于返回原数组值可行,对于返回对应下标不可行。

代码:

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

public class L001_Two_Sum {

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int target = in.nextInt();
        String[] str1 = str.split(" ");
        int[] nums = new int[str1.length];
        for(int i = 0;i<str1.length;i++){
            nums[i]=Integer.parseInt(str1[i]);
        }
        L001_Two_Sum ts = new L001_Two_Sum();
        int[] res = ts.twoSum(nums,target);
        System.out.println(res[0]+" "+res[1]);//输出两个下标值
        System.out.println(nums[res[0]]+" "+nums[res[1]]);//输出对应的数值
    }

    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
        //只会有一种解
        for(int i = 0;i<nums.length;i++)
            hm.put(target-nums[i],i);
        for(int j = 0;j<nums.length;j++){
            Integer v = hm.get(nums[j]);//value值,此处要用Integer不能用int,因为下面要和null比较
            if(v!=null&&v!=j){//null一定要写在前面,否则会引起NullPointerException异常
                return new int[]{j,v};
            }
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值