zoukankan      html  css  js  c++  java
  • N Sum


    题目:N 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.

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

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

    解决思路:像这种有关联关系的输入输出,C解决的话要考虑用哈希,Python的话我们直接考虑用字典解决就可以了,遍历数组,并且保存在字典中,查找字典中是否有符合的数字若符合直接返回数组下标和字典的value。 
    代码: 
    class Solution(object):  #这里我用Python解决
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dict = {}
            for i in xrange(len(nums)):
                x = nums[i]
                if target - x in dict:
                    return (dict[target - x],i)
                dict[x] = i

    知识点:

    range和xrange的区别

    >>> a = range(5)
    >>> print type (a)
    <type 'list'> #我们可以看出range生成的是一个list对象

    >>> print range(5)[0] #从list列表中打印list[0]
    0
    >>> b = xrange(5)
    >>> print type(b)
    <type 'xrange'>

    >>> print xrange(5)[0]#而xrange是一个xrange类型,不会直接生成一个list,而是在每次调用的时候返回其中的一个值,节省内存
    0               

  • 相关阅读:
    ORB-SLAM(五)优化
    ORB-SLAM(四)追踪
    ORB-SLAM(三)地图初始化
    SVM(支持向量机)的一点理解
    ORB-SLAM(二)性能
    ORB-SLAM(一)简介
    支持高并发的IIS Web服务器常用设置
    微信JS SDK Demo
    C#开发微信门户及应用-使用地理位置扩展相关应用
    DropdownListFor无法正确绑定值-同名问题
  • 原文地址:https://www.cnblogs.com/ylHe/p/6066538.html
Copyright © 2011-2022 走看看