最近在学python,正好拿leetcode的题来练练基本语法也顺便补补代码量。。。好久没写代码了。。。
题意大概是给一个数组和一个数,求两个下标使得这两个下标的数之和等于目标数。
直接循环一个数,然后检查另一个数在不在数组里并且不能是第一个数本身,用py自带的函数解决就行了
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
"""index = {};
idx = 0;
for i in nums:
index[i] = idx
idx+=1 """
lenNums = len(nums)
for i in range(0,lenNums):
ansx = nums[i];
ansy = target - ansx;
res = []
if (ansy in nums):
for j in range(0,lenNums):
if ansx == nums[j]:
res.append(j)
break
for j in range(0,lenNums):
if ansy == nums[j] and res[0] <> j :
res.append(j)
break
if len(res)>1 : return res
return res