#1 Two-sum

Description

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]的比较结果

其他解题方式

用哈希表可以对这道题进行很好的时间复杂度上的降低(当然空间复杂度飙升orz)
这里记录一下提供的两种源码和他们的思路

Two-pass Hash Table

class Solution {
    public int[] twoSum(int[] nums, int target) {
	    Map<Integer, Integer> map = new HashMap<>();
	    for (int i = 0; i < nums.length; i++) {
	        map.put(nums[i], i);
	    }
	    for (int i = 0; i < nums.length; i++) {
	        int complement = target - nums[i];
	        if (map.containsKey(complement) && map.get(complement) != i) {
	            return new int[] { i, map.get(complement) };
	        }
	    }
	    throw new IllegalArgumentException("No two sum solution");
	}
}

时间复杂度O(n),把数组信息存入hashmap的时间
总体想法是将存入数组的数字作为key,而将数组下标作为value,这样可以在查找target的时候,直接用target - num[i]作为查找源,通过判断value的存在与否以及value与当前坐标是否一致(这样一个数就用了两次,与题目不符)来查找对应答案

但是一开始有疑问,为什么能在hashmap中存入两个不一样的key值
后来发现他并没有做到存入两个不一样的key值,而是任由第二个value覆盖掉第一个value,因为在判断的时候用于查找的key是由target - num[i]得到,所以即使最终只有一个数据能进入hashmap,最终也能找到正确答案

eg. 当输入数据是[2, 2],4的时候,保存在map中的只有一个 pair[2, 1](数据2存在num[1]中),这个时候进入循环,在 i = 0 的时候计算出compliment = 2,送入map得到下标为1,发现不等于0,成功搜索

One-pass Hash Table

class Solution {
    public int[] twoSum(int[] nums, int target) {
	    Map<Integer, Integer> map = new HashMap<>();
	    for (int i = 0; i < nums.length; i++) {
	        int complement = target - nums[i];
	        if (map.containsKey(complement)) {
	            return new int[] { map.get(complement), i };
	        }
	        map.put(nums[i], i);
	    }
	    throw new IllegalArgumentException("No two sum solution");
	}
}

时间复杂度O(n)
代码顺序是:计算当前compliment,与之前塞入map中的key进行比较,如果有则退出,如果没有则将当前num塞入map

与方法一相比好理解了不少,亮点在于只需要与之前的数值进行比较,而不用对全局进行搜索,很大程度缩短了时间

其他

没什么别的了……回去好好看下java和C++对hashmap的实现orz
而且不管怎么说用字典然后下标和内容互换存key/value真的好难想到啊!要好好想想怎么在别的地方用QuQ
其实就是份leetcode记录……希望能努力刷完吧!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值