LeetCode 1. Two Sum (Easy)
来源:互联网 发布:单片机数码管接线 编辑:程序博客网 时间:2024/06/05 22:41
题目描述:
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的两个数字并输出其下标。
思路:暴力法:对于每个数组元素,判断剩余元素与其相加是否为target,复杂度O(n^2)
哈希法:设当前元素为x。遍历数组,如果target - x存在于哈希表,则输出其下标,复杂度O(n),即遍历数组的复杂度。因为我对c++的map不熟,就用python的dict来做了。
python代码(哈希):
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict = {} for i in range(len(nums)): if dict.get(target - nums[i], None) == None: dict[nums[i]] = i else: return (dict[target - nums[i]], i)
阅读全文
0 0
- leetcode 1. Two Sum [Easy]
- LeetCode 1. Two Sum (Easy)
- Leetcode[Easy] - Two Sum
- 【Leetcode】Two sum(easy)
- leetcode Two Sum easy
- Leetcode 1. Two Sum (Easy) (cpp)
- Leetcode 1. Two Sum (Easy) (java)
- Leetcode #1 Two Sum (easy)
- Leetcode #1 - Two Sum - Easy
- 【Easy】1. Two Sum
- 1. Two Sum easy
- 1. Two Sum (Easy)
- 1.[easy] Two Sum
- LeetCode解题报告 1. Two Sum[easy]
- Leetcode解题笔记 1.Two Sum [Easy]
- LeetCode第一关:Two Sum --> Difficulty: Easy
- LeetCode OJ 1 Two Sum [Easy]
- week1-leetcode #1-Two Sum[Easy]
- shell脚本连接、读写、操作mysql数据库实例
- XRecyclerView 上拉刷新、下拉加载
- golang -strconv包常用函数笔记
- 我的思维导图
- hiho一下 第167周
- LeetCode 1. Two Sum (Easy)
- LAMP之CentOS5_JDK安装
- Python 添加windows server服务程序
- Reverse String
- Elasticsearch 集群优化总结
- ImageLoader怎么用
- java.lang.instrument ASSERTION FAILED ***: "error == JVMTI_ERROR_NONE" at Reentrancy.c line: 161
- loadrunner可以使用非IE浏览器进行录制脚本
- 51Nod