LeetCode Python TwoSums

时间:2015-08-01 16:27:19

标签: python algorithm

我绝对是python上的菜鸟,刚开始练习leetcode。无论如何看看这个TwoSum练习:给定一个整数数组,找到两个数字,使它们加起来一个特定的目标数。

以下是本练习的代码:

class Solution(object):

    def __init__(self, nums, target):
        self.nums = nums
        self.target = target

    def twoSum(self):
        for i in range(len(self.nums)):
            for j in range(i+1, len(self.nums)):
                if self.nums[i] + self.nums[j] == self.target:
                    print "index1=" + str(i) + ", index2=" + str(j)

sample = Solution([2, 8, 7, 15], 9)
sample.twoSum()

任何人都可以帮助我如何回答leetcode算法?这个面试可以接受吗?感谢

9 个答案:

答案 0 :(得分:4)

我不会认为您的代码或itertools解决方案可以接受,因为它们都是O(n^2)。如果在面试中给出,面试官可能希望看到你做得比仅仅运行两个嵌套for循环更好。

我会使用hash table或排序数组,然后binary search答案。

哈希表伪代码

h = empty hash table
for each element e in array
  if target - e in hash table:
    we have a solution
  add e to hash table

这将具有复杂性O(n),受一些哈希表怪癖的影响:在最坏的情况下,它可以是O(n^2),但对于随机输入不应该发生。

二进制搜索伪代码

sort array
for each element e in array
  binary search for target - e, make sure it's not found at the same index
  if it is, check the before / after element

  or think how you can avoid this happening

这将永远是O(n log n)

如果复杂性无关紧要,那么itertools解决方案很不错,但您的代码也可以完成工作。

答案 1 :(得分:3)

此代码在面试中是可以接受的,但在现实生活中,您应该学会了解这些库。在此示例中,它是itertools.combinations

from itertools import combinations

for item in combinations([2, 8, 7, 15], 2):
    if sum(item) == 9:
        print item  # prints (2, 7)

答案 2 :(得分:1)

使用哈希表是最简单的解决方案:

class Solution(object):
def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    d = {}
    for i, n in enumerate(nums):
        if n in d:
            return [d[n], i]
        d[target - n] = i

享受

答案 3 :(得分:0)

您的解决方案使用嵌套循环,这可能会导致超时错误。您可以使用字典来优化性能。 这是我的解决方案:

class Solution:
    def twoSum(self, num, target):
        map = {}
        for i in range(len(num)):
            if num[i] in map:
                return map[num[i]], i
            else:
                map[target - num[i]] = i
        return -1, -1

更重要的是,你永远不应该修改公共方法签名。

答案 4 :(得分:0)

也许是O(n)

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """

    if target%2==0 and target/2 in nums:
        i=0
        for x in range(len(nums)):
            if nums[x]==target/2:
                i+=1
        if i>=2:
            return nums.index(target/2), nums.index(target/2, nums.index(target/2)+1)
    elif target==0:
        for x in nums:
            if -x in nums:
                return nums.index(x), nums.index(-x)
    else:
        for x in nums:
            if x!=target/2 and abs(x)<=abs(target) and target-x in nums:
                return nums.index(x), nums.index(target-x)

答案 5 :(得分:0)

天真,时间复杂度O(n ^ 2):

class Solution:
    def twoSum(self, nums, target):
        for i in range(0, len(nums)):
            to_find = target-nums[i]
            for j in range(0, len(nums)):
                if j!=i and nums[j] == to_find: 
                    return [i, j]
        return [-1, -1]

使用排序,时间复杂度O(nlogn):

class Solution:
    def twoSum(self, nums, target):
        nums = sorted(nums)
        for i in range(len(nums)):
            to_find = target - nums[i]
            left, ryt = 0, len(nums)-1
            while left<ryt:
                mid = (left+ryt)//2
                if mid != i and nums[mid] == to_find:
                    return [i, mid]
                elif nums[mid]>to_find:
                    ryt = mid-1
                else:
                    left = mid+1
        return [-1, -1]

使用两个指针排序,时间复杂度O(nlogn):

  • 上述排序方法的改进版本,但时间复杂度仍为O(nlogn)

使用哈希图,时间复杂度O(n):

class Solution:
    def twoSum(self, nums, target):
        num_to_idx = {}

        for i, num in enumerate(nums):
            if target-num in num_to_idx:
                return [i, num_to_idx[target-num]]
            num_to_idx[num] = i
        return [-1, -1]

答案 6 :(得分:0)

我已经使用字典来存储值/索引,因为在O(1)中可以在字典中搜索键。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict_nums = dict()
        for index, value in enumerate(nums):
            reminder = target - value
            if reminder in dict_nums:
                return [dict_nums[reminder], index]
            dict_nums[value] = index

时间复杂度:O(n)
空间复杂度:O(n)

答案 7 :(得分:0)

许多面试官要求解决O(n)时间复杂性的问题。 这是一个提示:-如果面试官要求您将时间复杂度从O(n ^ 2)降低到O(n)或O(n ^ 3)降低到O(n ^ 2),您可能会猜到您必须使用哈希表在这种情况下,持续60%的时间。您可以使用哈希表(在python中称为字典)轻松解决twoSum问题。这是我在python中的问题的解决方案,它比公认的问题快94%:-

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:   
        l = len(nums)
        my_dic = {}
        
        for i in range(l):
            t = target - nums[i]
            v=my_dic.get(t,-1)
            
            if v!=-1:
                if my_dic[t]!=i:
                    return [my_dic[t],i]
            else:
                my_dic[nums[i]] = i

        return []

如果您不了解解决方案,可以问我任何问题

答案 8 :(得分:0)

a = {}
    i = 0
    while i < len(nums):
        if nums[i] not in a.values():
            a[i] = target - nums[i]
        else:
            
            keys = list(a.keys())
            vals = list(a.values())
            key = keys[vals.index(nums[i])]
            return [i,key]
        i += 1
    
    return

使用字典你可以解决更好的时间复杂度

相关问题