zoukankan      html  css  js  c++  java
  • python leetcode

    """


    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].

    """
     
    第一种比较简单的方法
    class solution(object):
      def twoSum(self,listnums,target):
        for i in listnums:
          for j in listnums:
            if i != j:
              if target == i+j:
                return listnums.index(i),listnums.index(j)
                
     

    s = solution()
    s.twoSum([1,2,3,4],7)
     
    第二种比较好的方式
    class Solution(object):
      def twoSum(self, nums, target):
      dic = dict()
      for index,value in enumerate(nums):
        sub = target - value
        if sub in dic:
          return [dic[sub],index]
        else:
          dic[value] = index
     
     
    每个年龄,鞭策自己尽力前行的理由都不一样,大家且行且珍惜
  • 相关阅读:
    View Controller 生命周期的各个方法的用法
    IOS开发之Post 方式获取服务器数据
    委托代理
    Function
    SKPhysicsContactDelegate协议
    UITouch附加
    Remove Duplicates from Sorted Array II
    4Sum
    [Text Justification
    Count and Say
  • 原文地址:https://www.cnblogs.com/miss-saber/p/9394784.html
Copyright © 2011-2022 走看看