题目

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 银行系统

    目前代码只写到这 主要部分已经实现 功能部分展现 首先我们需要五个类 用户类  : 成员属性 name  id  以及 card 卡类: 成员属性 卡号  密码  余额   锁 界面类:   管理员界 ...

  2. wav2midi 音乐旋律提取算法 附可执行demo

    前面提及过,音频指纹算法的思路. 也梳理开源了两个比较经典的算法. https://github.com/cpuimage/shazam https://github.com/cpuimage/Aud ...

  3. 【CS】知识索引汇总

    Chapter 7 hello.o -> hello (链接) 一.静态链接 主要是将符号对应起来 两个主要任务:符号解析(符号引用与符号定义的对应).重定位(符号定义与内存位置的对应) 1. ...

  4. Hadoop守护进程的作用(转)

    概述: <ignore_js_op> Hadoop是一个能够对大量数据进行分布式处理的软件框架,实现了Google的MapReduce编程模型和框架,能够把应用程序分割成许多的 小的工作单 ...

  5. sql语句-6-更新数据

  6. 服务端调用接口API利器之HttpClient

    前言 之前有介绍过HttpClient作为爬虫的简单使用,那么今天在简单的介绍一下它的另一个用途:在服务端调用接口API进行交互.之所以整理这个呢,是因为前几天在测试云之家待办消息接口的时候,有使用云 ...

  7. CF 1083 C. Max Mex

    C. Max Mex https://codeforces.com/contest/1083/problem/C 题意: 一棵$n$个点的树,每个点上有一个数(每个点的上的数互不相同,而且构成一个0~ ...

  8. Yii2.0 技巧总结

    View部分 1. 使用ActiveField中的hint生成提示文字 <?= $form->field($model, 'freightAddedFee')->textInput( ...

  9. 洛谷P2831 愤怒的小鸟

    洛谷P2831 愤怒的小鸟 原题链接 题解 首先简单数学公式送上. \(ax_1^2+bx_1=y_1\) \(ax_2^2+bx_2=y_2\) \(ax_1^2x_2+bx_1x_2=y_1x_2 ...

  10. jenkins统计单元测试的覆盖率

    前提:单元测试和被测代码在一个仓库 maven的pom配置 依赖增加 <dependency> <groupId>org.jacoco</groupId> < ...