leetcode two-sum

来源:互联网 发布:平面设计好还是美工好 编辑:程序博客网 时间:2024/06/07 09:29
原题:

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。


原创粉丝点击