美文网首页
LeetCode每日一题:two sum

LeetCode每日一题:two sum

作者: yoshino | 来源:发表于2017-07-05 10:32 被阅读8次

    问题描述

    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

    问题分析

    the start of leetcode!
    通过hashmap来加快读取速度,键放target-每个数的结果,值放这个数的下标i。每次放入的时候考虑键是否存在,存在说明当前数的index和hashmap里的下标i即为所求。不过最后两个值都需要加1才是正确答案,详情见代码。

    代码实现

    public int[] twoSum(int[] numbers, int target) {
            int[] result = new int[2];
            HashMap<Integer, Integer> hashMap = new HashMap<>();
            for (int i = 0; i < numbers.length; i++) {
                if (hashMap.containsKey(numbers[i])) {
                    result[0] = hashMap.get(numbers[i]) + 1;
                    result[1] = i + 1;
                    break;
                } else hashMap.put(target - numbers[i], i);
            }
            return result;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:two sum

          本文链接:https://www.haomeiwen.com/subject/tcnfhxtx.html