前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >1. Two Sum(HashMap储存数组的值和索引)

1. Two Sum(HashMap储存数组的值和索引)

作者头像
yesr
发布2019-03-14 12:58:37
9310
发布2019-03-14 12:58:37
举报
文章被收录于专栏:leetcode_solutionsleetcode_solutions

Two Sum

【题目】

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

(给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的索引。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。)

Example:

代码语言:javascript
复制
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

【分析】

target是两个数字的和,而题目要求返回的是两个数的索引,所以我们可以用HashMap来分别储存数值和索引。

我们用key保存数值,用value保存索引。然后我们通过遍历数组array来确定在索引值为i处,map中是否存在一个值x,等于target - array[i]。如果存在,那么map.get(target - array[i])就是其中一个数值的索引,而i即为另一个。

以题目中给的example为例:

在索引i = 0处,数组所储存的值为2,target等于9,target - array[0] = 7,那么value =7所对应的key即为另一个索引,即i = 2

Java实现代码如下:

代码语言:javascript
复制
class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length < 2) return new int[] {-1, -1};
        int[] res = new int[] {-1, -1};
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Two Sum
  • 【题目】
    • Example:
    • 【分析】
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档