1. Two Sum
来源:互联网 发布:猴王水果竞猜网站源码 编辑:程序博客网 时间:2024/06/06 03:04
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
给定一个整数数组和一个目标值,返回两个数的索引,这两个数之和等于目标值
第一次尝试,最低效的方法
采用遍历的方法,时间复杂度为O(n^2),代码如下:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: return [i,j]
结果见下图(5516 ms):
别人家孩子的做法
在此之前,我想到过使用比较好的数据结构肯定可以简化实现过程,dict或者其他,但最终没有想到解决方案,于是在讨论区逛了逛,他们好过分,真的可以用dict来很简单的解决,思路是这样的:
- 将输入的整数数组转换为dict,key为数组中的值,value为该值对应的索引
- 对于每一个key,判断target-key是否在dict中,再则返回[key对应的value, target-key对应的value],如果不在则继续下一个
时间复杂度变成O(n),我的python实现如下:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ positions = dict(zip(nums, range(len(nums)))) for i in range(len(nums)): position = positions.get(target-nums[i], None) if position: return [i, position]
耗时只有上次的1/100,如下图(60 ms):
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- C#多线程网页采集器(Spider)
- sscanf函数 和cin流的问题
- 敏捷开发之srcum
- 生成验证码图片
- scrollTop兼容各个浏览器的办法
- 1. Two Sum
- .Net/C# 实现 中国移动 CMPP v3.0 ISMG <-> SP 收发短信的 SP 客户端 (CMPP SP Client)
- 雅虎股票接口 转载
- spring mvc + mybatis 整合框架
- LeetCode 114. Flatten Binary Tree to Linked List
- C#16位MD5加密算法
- (转)成功男人早晨有五个习惯
- 蓝桥杯b组c++.2
- 关联库文件出现的2个错误