博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode001 Two Sum
阅读量:2241 次
发布时间:2019-05-09

本文共 772 字,大约阅读时间需要 2 分钟。

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

思路:两个数的和一定(target),如果一个其中一个数字固定,那另一个数字也就固定了。

所以我用for循环,每次先固定一个数,再用index方法寻找另一个。(不能重复)

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """                 for i,val in enumerate(nums):            retarget = target - val            if retarget in nums and nums.index(retarget) != i:                j = nums.index(retarget)                return [i,j]

 

转载地址:http://hjrbb.baihongyu.com/

你可能感兴趣的文章
Oracle列转行函数 Listagg() 语法详解及应用实例
查看>>
LISTAGG函数的用法
查看>>
Oracle Spatial操作geometry方法
查看>>
IDEA类和方法注释模板设置(非常详细)
查看>>
Java程序初始化的顺序
查看>>
Dubbo和Spring结合配置文件内容解析为bean的过程
查看>>
fastJson注解@JSONField使用的一个实例
查看>>
fastjson的@JSONField注解的一点问题
查看>>
fastjson使用(三) -- 序列化
查看>>
浅谈使用单元素的枚举类型实现单例模式
查看>>
Java 利用枚举实现单例模式
查看>>
Java 动态代理作用是什么?
查看>>
Java动态代理机制详解(JDK 和CGLIB,Javassist,ASM) (清晰,浅显)
查看>>
三种线程安全的单例模式
查看>>
Spring AOP 和 动态代理技术
查看>>
从 volatile 说起,可见性和有序性是什么
查看>>
如何开始接手一个项目
查看>>
Netty 5用户指南
查看>>
Java实现简单的RPC框架
查看>>
一个用消息队列 的人,不知道为啥用 MQ,这就有点尴尬
查看>>