1.两数之和

本文共417字。
展开

题目描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

链接:https://leetcode-cn.com/problems/two-sum

方法1、暴力搜索

执行用时:20 ms

时间复杂度:O(n^2)

空间复杂度:O(1)

思路总结:循环遍历两次list,分别判断相加是否为target。

注意:for循环需要range(len),所以需要先得到list的len

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int] nums=[2,7,11,15]
:type target: int target = 9
:rtype: List[int] 暴力搜索 brute force way
"""
size = len(nums)
for i in range(size):
for j in range(i+1, size):
if nums[i]+nums[j]==target:
return [i,j]
return []

2、哈希表

执行用时:16 ms

时间复杂度:O()

空间复杂度:O()

思路总结:构建hash表,如hash表中有target-num,直接取;如果没有,先存入。存入的hash表,key=数组的值;value=数组的下标。

注意:for循环需要range(len),所以需要先得到list的len

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int] nums=[2,7,11,15]
:type target: int target = 9
:rtype: List[int] 哈希表 hash table
"""
hashtable = dict() # 构建hash table
for i,num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target-num], i]
hashtable[nums[i]] = i
return []