LeetCode - 1 python實現
阿新 • • 發佈:2019-01-05
題意:給你一個整型的列表nums和target,要求返回[i,j]滿足nums[i]+nums[j]=target
頭一回用py,求別黑..(連helloWorld都沒敲過QAQ
話說leetcode怎麼連資料範圍都沒有
ps.順便把輸入程式也搞出來了
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic0 = {} dic1 = {} length = len(nums) for i in range(length): if dic0.__contains__(nums[i])^dic1.__contains__(nums[i]) == True: # 1 0 dic1[nums[i]]=i elif dic1.__contains__(nums[i]) == False: # 0 0 dic0[nums[i]]=i for i in range(length): elem = nums[i] if target-elem == elem and dic1.__contains__(elem) == True: return [i,dic1[elem]] elif target-elem != elem and dic0.__contains__(target-elem) == True: return [i,dic0[target-elem]] ######################################## fileInput = [] with open('stdin.txt') as fp: for line in fp: fileInput.append(line) lis = fileInput[0].lstrip("[").rstrip("]\n").split(",") # 不是標準的列表形式 nums = [int(chars) for chars in lis] target = int(fileInput[1]) print(Solution.twoSum(Solution,nums,target))
input
[2,7,11,15]
9
output
[0,1]