zoukankan      html  css  js  c++  java
  • LeetCode-1- Two Sum

    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.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    简言之,查找给定数组内两个数,使得两数和为给定的target

     

    思路:

      遍历给定数组,用一个哈希表存放已经遍历过的值,key是nums中的值,value是其位置索引。

      对于当前遍历的nums[i],查找哈希表中是否存在target-nums[i],若存在,则返回二者索引,否则将(key=nums[i],value=i)放入哈希表中,继续遍历

     

    时间复杂度:O(n)

    python代码如下,已AC:

     1 class Solution(object):
     2     def twoSum(self, nums, target):
     3         """
     4         :type nums: List[int]
     5         :type target: int
     6         :rtype: List[int]
     7         """
     8         dictMap = {}
     9         for index, value in enumerate(nums):
    10             if target - value in dictMap:
    11                 return [dictMap[target - value] , index ]
    12             dictMap[value] = index

    提交结果:

  • 相关阅读:
    25.Zabbix入门必备
    6.Ansible Roles角色实战
    5.Ansible Jinja2 模板
    4.Ansible Task控制
    3.Ansible varialbes实战
    2.Ansible Playbook剧本
    1.Ansible自动化管理工具
    网站架构面试题必备
    winsows CMD及Linux命令大全 欢迎补充
    Oracle查询表空间
  • 原文地址:https://www.cnblogs.com/z941030/p/5608745.html
Copyright © 2011-2022 走看看