zoukankan      html  css  js  c++  java
  • 两数之和

    题目描述:

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
    你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
    示例:
    给定 nums = [2, 7, 11, 15], target = 9
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1] 
    思路:每次遍历一个元素,将元素添加到list中,并判断(target-元素)是否在list中,如果在,获取索引

    class
    Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ list=[] if not nums: return list for num in nums: list.append(num) res=target-num if res in list: i=list.index(res) j=nums.index(num) return [i,j] return []
  • 相关阅读:
    让人难以想出的动态转移方程小集
    初识DP
    CSP复赛day2模拟题
    通知
    未完成作业
    2019年东莞特长生 散步
    营救
    农场主
    安全密码
    开发区规划
  • 原文地址:https://www.cnblogs.com/whu-2017/p/9719464.html
Copyright © 2011-2022 走看看