美文网首页
001-two-sum

001-two-sum

作者: 在努力的Jie | 来源:发表于2018-03-07 17:04 被阅读0次

    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.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1]
    
    1. 方法一:时间复杂度O(n*n)
    class solution(object):
            def twosum(self,nums,target):
                    b =False
                    i =0
                    j =len(nums)-1
                    while j>0:
                            while i
                                    if not nums[i]+nums[j]==target :
                                            i +=1
                                    else :
                                            b=True
                                            print( i+1,j+1)
                                            break
                                j-=1
                        if not b:
                            print("null")
    sl=solution()
    sl.twosum([1,3,7,8],10)
    
    1. 方法二:网络转载(http://www.cnblogs.com/chruny/p/4788804.html
    
    class Solution(object):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
    
        def twosum(self,nums,target):
            b= False
            d ={}
            size = 0
            print(nums)
    
            while size < len(nums):
                if not int(nums[size]) in d:
                    d[int(nums[size])]=size+1
                if target - int(nums[size]) in d:
                    if d[target - int(nums[size])] < size+1:
                        b = True
                        ans = [d[target-int(nums[size])], size+1]
                        print(ans)
    
                size +=1
            if not b:
                print("null")
    
    sl=Solution()
    sl.twosum(nums=list(input("Please input a list: ")),target=int(input('And input a target:')))
    
    1. 笔记:
      • len(nums): nums中键值对的数量
      • dictionary:字典的增删改(http://www.runoob.com/python/python-dictionary.html),
        键必须是唯一的,但值则不必。
        值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组

    向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

    实例
    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
     
    dict['Age'] = 8; # update existing entry
    dict['School'] = "DPS School"; # Add new entry
    print "dict['Age']: ", dict['Age'];
    print "dict['School']: ", dict['School'];
    
    • boolean:定义一个boolean变量,默认为false,在其他条件中定义为ture

    相关文章

      网友评论

          本文标题:001-two-sum

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