lintcode刷题(python)——(4)
2017-05-18 06:29
309 查看
友情提示:点击上面的“+”展开目录以便查看具体的题目
Two Sum - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
注意事项
You may assume that each input would have exactly one solution.
样例
Given nums =
[2, 7, 11, 15],
target =
9
return
[1, 2]
这道题特别简单,唯一要注意的一点就是有相同数字时的处理,如[1,1,3,4] target=2,方法见下面代码。
class Solution: """ @param nums {int[]} n array of Integer @param target {int} = nums[index1] + nums[index2] @return {int[]} [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, nums, target): # Write your code here for i in range(len(nums)): if target-nums[i] in nums: if (target-nums[i])!=nums[i]: return [i+1,nums.index(target-nums[i])+1] else: if nums.count(nums[i])>1: return [i+1,nums.index(target-nums[i])+2]
相关文章推荐
- lintcode python代码 463 整数排序
- [Lintcode 3sum]三数之和(python,二分)
- [LintCode]Fibonacci(Python)
- python_lintcode_简单题_365.181.55
- [Lintcode 397] 最长上升连续子序列(Python)
- [LintCode]Remove Element(Python)
- [LintCode]Two Strings Are Anagrams(C++|Java|Python)
- [LintCode]Longest Common Prefix(Python)
- python_lintcode_困难题_54
- lintcode刷题-移动零 python
- lintcode python代码 433岛屿个数
- LintCode python 小白-简单题-638-Strings Homomorphism
- LintCode python 小白-简单题-423有效的括号序列
- lintcode python代码 420 报数
- lintcode 刷题-两数组的交 II Python
- lintcode刷题——python(栈)
- lintcode python代码 433岛屿个数
- [LintCode]Compare Strings(C++|Python)
- python_lintcode_简单题_8旋转字符_420报数_197排列序号
- LintCode Python 尾部的零