LeetCode题解 —— 1. Two Sum

题目内容:

Difficulty: Easy Total Accepted: 802.9K Total Submissions: 2.2M

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].

题目描述

已知一个整数数组nums和一个目标数值target,在数组中找到两个位置,使得该位置对应的数字之和等于target的值,结果返回这两个数在数组中的位置。注意:位置下标从0开始的。

解题思路及代码实现(java)

解法1. 暴力算法(穷举法)

这是首先想到的方法,也是最简单直接有效的方法。遍历数组中所有两个数之和,找到等于目标值的两个数并返回数组下标即可,若没找到则抛出一个异常。

public static int[] twoSum1(int[] nums, int target){
    int[] result = new int[2];
    for (int i = 0; i < nums.length; i++) {
        for (int j = i+1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    throw new IllegalArgumentException("No solution");
}

此方法虽然可行,但是时间复杂度有点高,耗时间。

解法2. 通过Hash表

在Hash表中key存放目标值与给定数组中每个数的差值,value存放出现的位置,然后循环遍历给定数组,在Hash表中找到等于差的数,存在则取出对应的索引,保存结果并返回。

public static int[] twoSum2(int[] nums, int target){
    int[] result = new int[2];
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if(map.containsKey(nums[i])){
            result[0] = map.get(nums[i]);
            result[1] = i;
            return result;
       } else
           map.put(target-nums[i], i);
    }
    throw new IllegalArgumentException("No solution");
}

提交后AC,时间复杂度O(n),运行时间明显比方法一快很多。
看网上应该还有其他方法,但我还没有细看与测试,目前代码只是用Java来实现,等有空了再详细研究以下其他方法的思路和用其他语言实现吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值