[DP]1.two sum
2018-01-29 10:55
99 查看
题目描述:
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:
这道题主要用的还是Python的内置函数index()
我觉得这个方法还是挺简单的。就是效率低,不过代码短。又好理解。
这里再记录两个Python里的常用函数:
map(f,nums)
第一个参数是一个函数f,作用在num的每一个元素上。
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].
这道题主要用的还是Python的内置函数index()
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ re = [0,0] for i in range(len(nums)): if (target - nums[i]) in nums[i+1:]: re[0] = i re[1] = nums[i+1:].index(target-nums[i])+(i+1) return re
我觉得这个方法还是挺简单的。就是效率低,不过代码短。又好理解。
这里再记录两个Python里的常用函数:
map(f,nums)
第一个参数是一个函数f,作用在num的每一个元素上。
>>> e = list(range(10)) >>> def f(num): ... return num+2 ... >>> list(map(f,e)) [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>>第二个函数是enumerate(nums),可以将Index和item一起输出
>>> list1 = [10,11,12,13,14] >>> for index,item in enumerate(list1): ... print(index,item) ... 0 10 1 11 2 12 3 13 4 14 >>>
相关文章推荐
- hdoj1074 Doing Homework(好题呀,状态压缩+DP)
- poj 3254 Corn Fields dp状态压缩
- Android : dip/dp与px(pixel)之间的相互转换
- hdu 3280 Equal Sum Partitions (区间dp)
- POJ 3616【数状数组求区间最大值 + 简单DP】
- hdu 4540 威威猫系列故事——打地鼠 dp小水题
- bzoj3156: 防御准备(斜率优化+Dp)
- 暑期dp46道(37) HDOJ 2844 COINS
- 最大子串和(dp)
- hdu 2196 树形dp
- hdu 5135(2014广州—状态dp)
- LightOj 1422 Halloween Costumes(区间DP)
- ural1057(数位DP)
- [数位dp] bzoj 3209 花神的数论题
- bzoj 1072(状压dp)
- Party at Hali-Bula - POJ 3342 树形dp
- hduoj-2084 数字塔问题 DP
- poj2817 状态dp(二进制存储)+记忆化搜索
- dp
- noip2016 d1t3 换教室 期望dp+floyd