美文网首页
leetcode 1 遍历算法

leetcode 1 遍历算法

作者: 在做算法的巨巨 | 来源:发表于2018-09-05 19:20 被阅读0次

1. 两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路:

如果不考虑数组是否是有序数组还是无序数组,就采用array遍历的方法,这里需要避免重复遍历,时间复杂度是O(n^2)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)-1):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return([i,j])

这种方法是通过牺牲时间换取空间,也可以尝试下面的方法,通过构建哈希表,不断的向里边插入值和index。通过牺牲空间来换取时间。

思路:
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        table = []
        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in table:
                return(i, table.index(complement))
            table.append(nums[i])

这里的时间复杂度是O(n)

相关文章

  • leetcode 1 遍历算法

    1. 两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,...

  • Leetcode二叉树题目分类(长期更新)

    树的遍历构造 Leetcode 105. 从前序与中序遍历序列构造二叉树(分治算法)Leetcode 106. 从...

  • 回溯,贪心,动态规划

    1.回溯算法思想leetcode 112 号算法题:路径总和leetcode 113 号算法题:路径总和 IIle...

  • 回溯的例子-正则表达式

    回溯 回溯是比较强有力的遍历或枚举算法,掌握这个算法别无他途,只有勤学多练。在leetcode中的第10题就是一个...

  • LeetCode问题图解-1

    本文准备讲解1个算法编程问题, 这个算法编程问题来自LeetCode平台。不了解.LeetCode平台的读者可以...

  • ARTS第三周(2018-12-16)

    1.Algorithm:每周至少做一个 leetcode 的算法题 第一道算法题:https://leetcode...

  • Leetcode(栈的题解)

    Leetcode_20 括号匹配 Leetcode_144 前序遍历

  • 三叉链表的遍历算法

    1. 不借助栈的非递归中序遍历算法 2. 不借助栈的非递归后序遍历算法

  • LeetCode 226 (Invert Binary Tree

    LeetCode:226 invert-binary-tree先序遍历: 中序遍历: 后序遍历: 层序遍历:

  • LeetCode基础算法-数组

    LeetCode基础算法-数组 算法 LeetCode 数组相关 1. 从排序数组中删除重复项 描述:给定一个排序...

网友评论

      本文标题:leetcode 1 遍历算法

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