関数式leetcode-1

1143 ワード

pythonバージョン、2.7
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if target % 2 == 0 :
            result = []
            for index,item in enumerate(nums):
                if len(result) == 2:
                    return result
                if item * 2 == target:
                    result.append(index)
            if len(result) == 2:
                return result
        my_set = set(nums)
        result_set = filter(lambda x:(target - x) in my_set and x * 2 != target,my_set)
        num = result_set[0]
        result = []
        for index,item in enumerate(nums):
            if len(result) == 2:
                return result
            if item == num or item == target - num:
                result.append(index)
        result.sort()
        return result
if __name__ == '__main__':
    test = Solution()
    #result = test.twoSum([3,2,4],6)
    #result = test.twoSum([0,4,3,0],0)
    result = test.twoSum([2,1,9,4,4,56,90,3],8)
    print(result)