# 从零开始刷LeetCode

No.1两数之和

Java

public int[] twoSum(int[] nums,int target) {

for(int i =; i

for(int j = i +1; j

if(nums[j] == target - nums[i]) {

returnnew int[] { i,j };

}

}

}

throw new IllegalArgumentException("No

two sum solution");

}

publicint[] twoSum(int[] nums,inttarget) {

Map map = new HashMap();

for(inti =; i

map.put(nums[i],i);

}

for(int i =; i

int complement = target - nums[i];

if(map.containsKey(complement) &&

map.get(complement) != i) {

returnnewint[] {

i,map.get(complement) };

}

}

throw new IllegalArgumentException("No

two sum solution");

}

publicint[] twoSum(int[] nums,inttarget) {

Map map = new HashMap();

for(inti =; i

intcomplement = target - nums[i];

if(map.containsKey(complement)) {

returnnewint[] {

map.get(complement),i };

}

map.put(nums[i],i);

}

throw new IllegalArgumentException("No

two sum solution");

}

Python

class Solution:

deftwoSum(self,nums,target):

"""

:typenums: List[int]

:typetarget: int

:rtype: List[int]

"""

n =len(nums)

forxinrange(n):

foryinrange(x+1,n):

ifnums[y] == target - nums[x]:

returnx,y

break

else:

continue

classSolution:

deftwoSum(self,nums,target):

"""

:typenums: List[int]

:typetarget: int

:rtype: List[int]

"""

n =len(nums)

forxinrange(n):

a = target - nums[x]

ifainnums:

y = nums.index(a)

ifx == y:

continue

else:

returnx,y

break

else:

continue

classSolution:

deftwoSum(self,nums,target):

"""

:typenums: List[int]

:typetarget: int

:rtype: List[int]

"""

num_dict =

print(num_dict)

num_dict2 =

print(num_dict2)

result = []

foriinrange(len(nums)):

j = num_dict.get(num_dict2.get(i))

if(jis not None)and(j != i):

result = [i,j]

break

returnresult

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20180920G0EAXC00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2022-01-18

2018-03-27

2022-01-18

2022-01-18

2022-01-18

2022-01-18

2022-01-18