• Leetcode 001: 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, and you may not use the same element twice.

    例子:

     [2,7,11,15], 9  输出 [0, 1]

    思路:

      主要考虑:

        1、是否有重复得如 [3,2,4] 6 得情况,不要输出[0, 0] ,题目中说明:you may not use the same element twice.

        2、考虑不同方法主要有三种:暴力,两遍哈希表和一遍哈希表。

    下面给出我的实现:

       两遍哈希表:

    #coding:utf-8
    
    '''
        leetcode 001 question
        author: xuyaowen time: 2018-04-02 
        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.
    '''
    class Solution(object):
        def twoSum(self, nums, target):
            pair = dict(zip(nums,range(len(nums))))
            for i in range(len(nums)):
                p =  target - nums[i]
                if  p in nums:
                    if p == target/2 and pair[p] == i:
                        continue
                    return [i, pair[p]] #所有的解对应当下的坐标
    # 1319 ms 时间效率很慢
    # 解决方法,两遍哈希表
    ans =  Solution()
    print(ans.twoSum([3, 3], 6))

      一遍哈希表:

    #coding:utf-8
    
    '''
        leetcode 001 question
        author: xuyaowen time: 2018-04-02 
        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.
    '''
    class Solution(object):
        def twoSum(self, nums, target):
            seen = {}
            for i, n in enumerate(nums):
                o = target-n
                if o in seen:
                    return [seen[o], i]
                seen[n] = i
    # 40ms
    # 一遍哈希表
    ans =  Solution()
    print(ans.twoSum([2, 7, 11, 15], 9))

      暴力算法就不展示了。

         更多得代码请参见: https://github.com/yaowenxu/Leetcode

      转载请注明出处

  • 相关阅读:
    Zabbix 最新安装视频
    Centos大文件切割和合并
    Docker 基础
    Docker的安装及加速
    mysql/MariaDB 搭建后创建密码及开启远程
    zabbix 添加 ROS 软路由监控 WinBox设置
    解决zabbix3.4X图形页面中文乱码
    Redis 4.0+安装及配置
    Zabbix3.4服务器的搭建--CentOS7
    CentOS 7 Nginx+PHP环境搭建!
  • 原文地址:https://www.cnblogs.com/xuyaowen/p/leetcode-001.html
Copyright © 2020-2023  润新知