Two Sum --- LeetCode 面试题

来源:互联网 发布:飞升碧水圣麒麟数据 编辑:程序博客网 时间:2024/05/16 14:49
题目原文: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中,找出2个数,其和为target,并将2个数的下标(index1,index2)作为数组返回。(要求:index1 < index2,且数组的下标从1开始。题目保证每一个输入总有唯一的输出)
    看到这个题目后,我脑中第一个蹦出来的想法就是,做2次遍历,记录和为target的2个数的下标,然后输出,不到10分钟,程序经过调试后,结果没问题,一提交,结果是 Time Limit Exceeded,由于该方法的运行时间是O(n^2),肯定不行。
    苦思冥想N久,想到如下方法:
        先将小于target的数字以及下标保存下来,然后在这些保存下的数字中做2次遍历,但是在最糟糕的情况下,结果还是 O(n^2),不行。
    通过查看LeetCode中对于该题的讨论,找到了解题方法,时间复杂度为O(n))思路如下:
        新建一个HashMap<Integer,Integer> hashMap,保存遍历过的numbers中元素的下标以及target与其差(作为key),
        遍历数组numbers,如果hashMap中的关键字中存在该元素,则说明找到所需的2个数字,否则在hashMap中的key保存target减numbers[i],value保存当前的下标,

程序实现代码(已通过,仅供参考):

package xtu.cie.ldj;import java.util.HashMap;public class TwoSumTest {    public static int[] twoSum(int[] numbers, int target) {    int[] result = new int[2];        HashMap<Integer, Integer> hashMap = new HashMap<Integer,Integer>();        for(int i = 0; i < numbers.length; i++){    if (hashMap.containsKey(numbers[i])) {int index = hashMap.get(numbers[i]);result[0] = index + 1;result[1] = i + 1;    break;}else {hashMap.put(target - numbers[i], i);}    }        return result;    }public static void main(String[] args) {// TODO Auto-generated method stub/*int [] testData = new int[32044 / 2 + 1];int count = 0;for (int i = 0; i <= 32044; i++) {if(i % 2 == 0){testData[count++] = i;}}int target = 16021;*/int[] testData = {-3,4,3,90};int target = 0;int[] result = new int[2];result = twoSum(testData, target);System.out.println("\n" + result[0] + "  " + result[1]);System.out.println("\n" + testData[result[0]-1] + "  " + testData[result[1]-1]);}}


0 0