[1] Two Sum

本贴最后更新于 2302 天前,其中的信息可能已经斗转星移

题目

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:

Given nums = [2, 7, 11, 15], target = 9, Because nums[**0**] + nums[**1**] = 2 + 7 = 9, return [**0**, **1**].

解法

一:暴力搜索

两个for循环即可

二:使用 HashMap

思路

for循环数组,从HashMap中查找结果,找到则返回结果,否则将该位放入HashMap

代码

class Solution { public int[] twoSum(int[] nums, int target) { HashMap, Integer> map = new HashMap<>(); int[] result = new int[2]; map.put(nums[0], 0); for (int i = 1; i < nums.length; i++) { boolean key = map.containsKey(target - nums[i]); if (key) { result[0] = map.get(target - nums[i]); result[1] = i; break; } map.put(nums[i], i); } return result; } }
  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1063 引用 • 3455 回帖 • 163 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖 • 1 关注
  • Easy
    101 引用 • 10 回帖

相关帖子

回帖

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...