leetcode 1 Two Sum(Easy)

1. Description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

2. Analysis

暴力解:遍历数组中所有的组合,判断是否存在两数之和为target——双重循环,外层循环遍历数组,内层循环遍历外层循环选定元素后的元素,循环体中判断外层和内层选中的元素之和是否为target

优化解空间换时间):要想减少时间复杂度,则需要只遍历一次数组。维护一个HashMap,从第二个元素开始遍历数组时判断hashMap中是否存在target - nums[i](),若存在,说明在当前元素和之前的元素中找到解;若不存在,则将(nums[i], i)存入hashMap,供后续元素查找。

3. Code

class Solution{
	// brute force
	public int[] twoSum(int[] nums, int target){
		int len = nums.length;
		for(int i = 0; i < len - 1; i++){
			for(int j = i + 1; j < len; j++){
				if(nums[i] + nums[j] == target){
					return new int[]{i, j};
				}
			}
		}
		throw new IllegalArgumentException("no solution");
	}
	
	// 优化解
	public int[] twoSum(int[] nums, int target){
		int len = nums.length;
		// 从第二个数开始才有可能存入hashmap,故容量只需len-1
		HashMap<Integer, Integer> hashMap = new HashMap<>(len - 1);
		hashMap.put(nums[0], 0);
		for(int i = 1; i < len; i++){
			int theOther = target - nums[i];
			if(hashMap.containsKey(theOther)){
				return new int[]{i, hashMap.get(theOther)};
			}
			hashMap.put(nums[i], i);
		}
		throw new IllegalArgumentException("no solution");
	}
	
	// 以下代码需要创建大小为n的hashmap,速度比上一方法稍慢
    public int[] twoSum(int[] nums, int target){
		int len = nums.length;
		HashMap<Integer, Integer> hashMap = new HashMap<>();
		for(int i = 0; i < len; i++){
            hashMap.put(nums[i], i);
        }
        for(int i = 0; i < len; i++){
			int other = target - nums[i];
            if(hashMap.containsKey(other) && hashMap.get(other) != i){
                return new int[]{i, hashMap.get(other)};
            }
        }
        throw new IllegalArgumentException("no solution");
	}
}

4. Complexity

TimeSpace
暴力解O(n^2)O(1)
优化解O(n)O(n)

暴力解:双重for循环,两层都与数组长度相关;只使用了常数个变量
优化解:单循环;维护了一个hashMap,容量与数组长度相关

5. Summary

一般情况下,会先将数组排序再使用双指针法,但本题告诉我们也可以使用HashMap进行处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值