题目

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].

翻译

给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。

你可以假定每个输入,都会恰好有一个满足条件的返回结果。

Hints

Related Topics: Array, Hash Table

如果简单地想O(n^2)的算法很容易实现

但是可以利用Hash Table来实现O(n)的算法

代码

Java

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> mymap = new HashMap<>();
for(int i=0;i<nums.length;i++){
Integer index = mymap.get(target-nums[i]);
if(index==null){
mymap.put(nums[i],i);
}else{
return new int[]{i,index};
}
}
return new int[]{0,0};
}
} //solution from discuss
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[1] = i + 1;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i + 1);
}
return result;
}
}

Python

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
mymap = {}
for i in range(len(nums)):
if nums[i] in mymap:
return [mymap[nums[i]],i]
else:
mymap[target-nums[i]] = i
return [0,0]

蜗牛慢慢爬 LeetCode 1.Two Sum [Difficulty: Easy]的更多相关文章

  1. 蜗牛慢慢爬 LeetCode 9. Palindrome Number [Difficulty: Easy]

    题目 Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could nega ...

  2. 蜗牛慢慢爬 LeetCode 20. Valid Parentheses [Difficulty: Easy]

    题目 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the i ...

  3. 蜗牛慢慢爬 LeetCode 7. Reverse Integer [Difficulty: Easy]

    题目 Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have ...

  4. 蜗牛慢慢爬 LeetCode 16. 3Sum Closest [Difficulty: Medium]

    题目 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...

  5. 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]

    题目 The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows li ...

  6. 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  7. 蜗牛慢慢爬 LeetCode 36.Valid Sudoku [Difficulty: Medium]

    题目 Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  8. 蜗牛慢慢爬 LeetCode 23. Merge k Sorted Lists [Difficulty: Hard]

    题目 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity ...

  9. 蜗牛慢慢爬 LeetCode 15. 3Sum [Difficulty: Medium]

    题目 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...

随机推荐

  1. 树莓派3B+SimpleCV上连接iPhone4s摄像头

    目的:把iPhone4s当成网络摄像头,通过wifi连接到树莓派上,做为树莓派的摄像头. 1. iPhone4s上安装mini WebCam应用. 很旧的一个app, 没有密码,简单,无广告,免费. ...

  2. Python 1.3 元组与文件

    一 Python元组Tuple类型 元组T= (1, 2, 3, 4)是不可变类型,属于序列,但顶层元素不可变,仅支持count()和index()操作. -*- coding:UTF- -*- # ...

  3. (数据科学学习手札51)用pymysql来操控MySQL数据库

    一.简介 pymysql是Python中专门用来操控MySQL数据库的模块,通过pymysql,可以编写简短的脚本来方便快捷地操控MySQL数据库,本文就将针对pymysql的基本功能进行介绍: 二. ...

  4. dtree的自定义select动作

    项目中用到了dtree,别问我为什么用这么古老的插件,因为简单啊orz,文件树的条目不多,detree加载卡顿的问题也不用解决,开森. 在使用过程中在选择节点后需要自定义一些onclick的动作,本来 ...

  5. Redis安装——在CentOS7下的安装

    参考自:https://linux.cn/article-6719-1.html 一.安装 首先通过xshell5先登陆来到字符界面(xshell通过SSH连接请参见之前随笔) 先下载redis,这里 ...

  6. 考研编程练习----m叉树先序和后序所包含的情况

    题目描述: We are all familiar with pre-order, in-order and post-order traversals of binary trees. A comm ...

  7. WPF 带水印的密码输入框

    原文:WPF 带水印的密码输入框 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/BYH371256/article/details/83652540 ...

  8. 【LG4631】[APIO2018]Circle selection 选圆圈

    [LG4631][APIO2018]Circle selection 选圆圈 题面 洛谷 题解 用\(kdt\)乱搞剪枝. 维护每个圆在\(x.y\)轴的坐标范围 相当于维护一个矩形的坐标范围为\([ ...

  9. 解决老项目中 Timer运行一段时间后失效的问题

    那是因为Timer中的代码出现了异常未被捕获,所以线程被挂起 只需要加入  try catch即可 推荐使用 Quartz 2018-08-08 03:50:44 [ Timer-1:39366015 ...

  10. 四、利用EnterpriseFrameWork快速开发基于WCF为中间件的三层结构系统

    回<[开源]EnterpriseFrameWork框架系列文章索引> EnterpriseFrameWork框架实例源代码下载: 实例下载 本章内容与上一张<利用Enterprise ...