twoSum Algorithm : How to improve this?

前端 未结 22 2368
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

Given an array of integers, find two numbers such that they add up to a specific target num

22条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-06 02:14

    One line solution in python :

    class Solution(object):
        """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
        """
        def twoSum(self, nums, target):            
            x = [[i, nums.index(target-j)] for i,j in enumerate(nums) if nums.count(target-j) > 0 and nums.index(target-j)!=i]
    
            return x.pop()
    

提交回复
热议问题