您的位置:首页 > 编程语言 > Python开发

LeetCode 1. Two Sum

2016-08-27 19:38 369 查看
题目:   

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].


题意:

在数组中返回2个数之和为目标数的下标。

题解:(By python)

1. 两次循环求解

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]
此复杂度为O(n^2)。

2. 使用python字典存储方式

    格式----   数值:对应下标

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
all = {} #定义字典
for item in range(len(nums)):
if target-nums[item] in all:
return [all[target-nums[item]],item]
all[nums[item]]=item  #存入字典


此复杂度为O(n)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Python