题目

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. python多进程详解和协程

    1.由于python多线程适合于多IO操作,但不适合于cpu计算型工作,这时候可以通过多进程实现.python多进程简单实用 # 多进程,可以cpu保持一致,python多线程适合多io.对于高cpu ...

  2. sublime install package没反应,以及安装后没有出现install package选项

    离线安装Package Control 一般出现这种问题的是网络原因,我们可以下载离线安装包 连接地址:https://github.com/wbond/package_control 安装完成后解压 ...

  3. 坚果云WebDav示例

    坚果云WebDav示例 最近看到坚果云有一个WebDAV应用,一时不解这是什么功能,了解后做了一个示例: WebDAV是一种基于HTTP1.1协议的通信协议.它扩展了HTTP1.1,在GET.POST ...

  4. ubuntu下tensorflow安装

    1,安装驱动,cuda,cudnn,参考本人上一篇博客http://www.cnblogs.com/zxg-DL/p/9023601.html 2,安装tensorflow   接下来是关于Tenso ...

  5. uni-app 下拉至指定高度固定view

    uni.createSelectorQuery().select(‘#salyt’).boundingClientRect(function(rects){ console.log(rects) va ...

  6. vector的二维用法+前缀和

    题目链接:https://codeforces.com/contest/1082/problem/C(C. Multi-Subject Competition) A multi-subject com ...

  7. 单线程的redis为什么吞吐量可以这么大

    原文:单线程的redis为什么吞吐量可以这么大 一.Redis的高并发和快速原因 1.redis是基于内存的,内存的读写速度非常快: 2.redis是单线程的,省去了很多上下文切换线程的时间: 3.r ...

  8. 【LG3243】[HNOI2015]菜肴制作

    题面 洛谷 题解 首先我们有个非常显然的思路, 就是直接拓扑排序,用小根堆代替队列再按顺序输出,但是很显然是错的, 因为这只保证了字典序最小,而无法保证答案最优,\(<2,4>,<3 ...

  9. Android:制作聊天气泡点9图

    步骤一:选择res下的一张图片,右击选择“Create 9-Patch File” 步骤二:确定点9图的名字,只能修改.9.png之前的信息 步骤三:在同目录下会生成刚才创建的点9图,双击打开进行编辑 ...

  10. Django——test文件编写接口测试

    用自己建立的小网页来做接口测试,在Django的tests.py写下如下 test_login_page为用get方式登录login路径,根据回复验证是否查看到页面 test_login_action ...