# coding = utf-8
'''
Created on 2015年11月9日
@author: SphinxW
'''
# 给一个整数数组,找到两个数使得他们的和等于一个给定的数target。
#
# 你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是1到n,不是以0开头。
# 样例
#
# numbers=[2, 7, 11, 15], target=9
#
# return [1, 2]
# 注意
#
# 你可以假设只有一组答案。
class Solution:
"""
@param numbers : An array of Integer
@param target : target = numbers[index1] + numbers[index2]
@return : [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, numbers, target):
# write your code here
father = [item for item in numbers]
numbers.sort()
headIndex = 0
tailIndex = len(numbers) - 1
while headIndex < tailIndex:
sum = numbers[headIndex] + numbers[tailIndex]
if sum == target:
h = father.index(numbers[headIndex])
numbers[headIndex] = "a"
t = father.index(numbers[tailIndex])
if h > t:
h, t = t, h
return [h + 1, t + 1]
if sum > target:
tailIndex -= 1
if sum < target:
headIndex += 1
LintCode_chapter2_section9_two-sum
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Problem More DiscussionsGiven an array of integers, find ...
- 原题 找到两个数字使得他们和最接近target 样例nums = [-1, 2, 1, -4],target = ...
- 原题 给一组整数,问能找出多少对整数,他们的和大于一个给定的目标值。 样例对于 numbers = [2, 7, ...