zoukankan      html  css  js  c++  java
  • 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

      转载请注明出处

  • 相关阅读:
    ios数据处理 简单文件处理
    ios硬件开发 照相机图像选取器(UIImagePickerController)的用法
    ios UI设计与开发 卷动视图
    ios数据处理 使用SQLite保存学生信息
    ios数据处理 Application preferfences
    ios数据处理 SQLite基本知识
    GDI+ 为了阴影和透明,使用双层窗口遇到的一些问题
    MFC CToolTipCtrl 总是显示
    遍历删除文件夹及文件
    WebService远程调试
  • 原文地址:https://www.cnblogs.com/xuyaowen/p/leetcode-001.html
Copyright © 2011-2022 走看看