leetcode two-sum

原题:

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

题意:经典问题,给定一个数组numbers(数组不一定有序) 和target,从数组中找到两个数,其和为target(假设解是唯一的)

思路:

最简单的解法,暴力搜索,对数组中任意两个数作加法,找到符合要求的解。时间复杂度O(n^2),空间复杂度 O(1)

第二种方法是维护一个哈希表,每遍历到一个数字m,去哈希表里找是否存在target-m,若找到则直接返回,若没有找到,则将该数加入到hash表中。要注意的地方是,遇到重复的数字就不再加入表当中。时间复杂度为O(n),空间复杂度为O(n)。相对于暴力搜索的时间复杂度降低很多

import java.util.Map;
import java.util.HashMap;
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    	for(int i = 0;i<numbers.length;i++)
        {
        	if(map.containsKey(target - numbers[i]))//一定要先判断是否存在
        	{
        		result[0] = map.get(target - numbers[i]) + 1;
        		result[1] = i + 1;
        		break;
        	}
        	map.put(numbers[i], i);
        }
    	return result;
    }
}

有一点需要注意的是,一定要先判断一个数的target-number[i],再将这个数加入hash表,如果倒过来会怎么样呢?

举个例子,比如target = 6,当前有一个数是3,你先将3加入了hash表,然后再去查找 6 - 3是否在hash表中,此时便找到了3,但此时你操作的是同一个数。(此时从hash表找到的3是你刚刚加入到hash表的3,是同一个数,并非两个数)因此一定要先判断,再put。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值