美文网首页
[easy][Array][遍历时用hash存信息]1.Two

[easy][Array][遍历时用hash存信息]1.Two

作者: 小双2510 | 来源:发表于2017-11-24 13:18 被阅读0次

原题是:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路是:

这一题,需要返回满足条件的元素的坐标,数组不能排序。
如果降低暴力解法的时间复杂度呢。
想到用哈希来存储遍历时的信息,用空间来换时间。
下面是我自己的代码,最后是一个值得借鉴的别人的代码。
我代码中,需要注意重复元素的问题。

代码:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dicts = {}
        result = []
        for i in range(len(nums)):
            if nums[i] not in dicts:
                dicts[nums[i]] = [i]
            else:
                dicts[nums[i]].append(i)
                
            if target - nums[i] in dicts and target - nums[i] != nums[i]:
                result.append(dicts[target - nums[i]][0])
                result.append(i)
                return result
            elif target - nums[i] == nums[i]:
                if len(dicts[nums[i]]) >1:
                    return dicts[nums[i]][0:2]
                
                
        return -1

别人的代码优秀在于:
1.使用enumerate来遍历,可以同时操作Index,和元素的值。
2.逻辑更简单,避免和统一了一些特殊情况。


Screen Shot 2017-11-24 at 12.13.42 AM.png

相关文章

网友评论

      本文标题:[easy][Array][遍历时用hash存信息]1.Two

      本文链接:https://www.haomeiwen.com/subject/iroxbxtx.html