Leetcode系列之两数之和
Leetcode系列之两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
链接:https://leetcode-cn.com/problems/two-sum/
Python实现(三种方法)
class Solution(object):
@staticmethod
def two_sum_1(nums: list, target: int):
"""方法一"""
for index1, num1 in enumerate(nums):
num2 = target - num1
if num2 in nums and nums.index(target - num1) != index1:
return [index1, nums.index(target - num1)]
@staticmethod
def two_sum_2(nums: list, target: int):
"""方法二"""
num_dict = {}
for index, num in enumerate(nums):
num_dict[num] = index
for i, num in enumerate(nums):
j = num_dict.get(target - num)
if j and i != j:
return [i, j]
@staticmethod
def two_sum_3(nums: list, target: int):
"""方法三"""
num_dict = {}
for index, num in enumerate(nums):
if target - num in num_dict:
return [num_dict[target - num], index]
num_dict[num] = index
go语言实现
package main
import "fmt"
func twoSum(nums []int, target int) []int {
maps := make(map[int]int) // map数据定义
nes := make([]int, 0) // 切片数据定义
for key, val := range nums {
ant := target - val
_, st := maps[ant]
if st {
nes = append(nes, maps[ant]) // 切片添加
nes = append(nes, key)
return nes
}
maps[val] = key
}
return nes
}
func main() {
nums := []int{2, 7, 11, 15}
target := 9
ret := twoSum(nums, target)
fmt.Println(ret)
}
- 执行结果
| 方法 | 执行用时 | 内存消耗 | 语言 |
|---|---|---|---|
| Python1 | 1168 ms | 14.9 MB | Python3 |
| Python2 | 68 ms | 15.4 MB | Python3 |
| Python3 | 68 ms | 15 MB | Python3 |
| go | 4 ms | 3.7 MB | Golang |
从执行结果可以看到,go语言的执行速度最快,内存消耗最少,执行速度和内存消耗明显有自身的优势。而Python实现的三种方法中,方法一的时间复杂度为O(n2),列表循环时间复杂度为O(n),每一次循环内都会进行一次判断
if num2 in nums and nums.index(target - num1) != index1:
in 列表查询的时间复杂度为O(n),因此整体时间复杂度为O(n2).方法二和方法三的时间复杂度为O(n),有人也许会说方法二和三的for循环中查询不是也要花费时间吗?我们带着问题去看一下方法二:
"""方法二"""
num_dict = {}
for index, num in enumerate(nums):
num_dict[num] = index
for i, num in enumerate(nums):
j = num_dict.get(target - num)
if j and i != j:
return [i, j]
两个for循环为O(n),字典赋值为O(1),字典查询为O(1)因此,整体时间复杂度为O(n)。
"""方法三"""
num_dict = {}
for index, num in enumerate(nums):
if target - num in num_dict:
return [num_dict[target - num], index]
num_dict[num] = index
方法三种in 字典时间复杂度为O(1),我们注意到这和方法一in 列表的O(n2)不同,字典查询确实比列表查询的效率高。
总结:不同语言之间的性能差异确实很大,尤其对于Python和go而言。go的性能确实无可挑剔,堪比C。但同时同一个题,同一种算法,python实现起来确实比较清爽,节省的时间、精力确实是python的优势,可以让人专注于程序的设计与思考,而不是各种复杂语法的实现。当然,不同语言各有优劣,社会需要什么,我们就去学什么,这才是王道!
Leetcode系列之两数之和的更多相关文章
- 每日一道 LeetCode (1):两数之和
引言 前段时间看到一篇刷 LeetCode 的文章,感触很深,我本身自己上大学的时候,没怎么研究过算法这一方面,导致自己直到现在算法都不咋地. 一直有心想填补下自己的这个短板,实际上又一直给自己找理由 ...
- Newtonsoft.Json C# Json序列化和反序列化工具的使用、类型方法大全 C# 算法题系列(二) 各位相加、整数反转、回文数、罗马数字转整数 C# 算法题系列(一) 两数之和、无重复字符的最长子串 DateTime Tips c#发送邮件,可发送多个附件 MVC图片上传详解
Newtonsoft.Json C# Json序列化和反序列化工具的使用.类型方法大全 Newtonsoft.Json Newtonsoft.Json 是.Net平台操作Json的工具,他的介绍就 ...
- leetcode刷题--两数之和(简单)
一.序言 第一次刷leetcode的题,之前从来没有刷题然后去面试的概念,直到临近秋招,或许是秋招结束的时候才有这个意识,原来面试是需要刷题的,面试问的问题都是千篇一律的,只要刷够了题就差不多了,当然 ...
- LeetCode :1.两数之和 解题报告及算法优化思路
最近开始重拾算法,在 LeetCode上刷题.顺便也记录下解题报告以及优化思路. 题目链接:1.两数之和 题意 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 ...
- LeetCode 167:两数之和 II - 输入有序数组 Two Sum II - Input array is sorted
公众号: 爱写bug(ID:icodebugs) 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index ...
- LeetCode | No.1 两数之和
题目描述: Given an array of integers, return indices of the two numbers such that they add up to a speci ...
- leetCode刷题 | 两数之和
两数之和: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数 ...
- leetcode算法1.两数之和
哈喽!大家好,我是[学无止境小奇],一位热爱分享各种技术的博主! [学无止境小奇]的创作宗旨:每一条命令都亲自执行过,每一行代码都实际运行过,每一种方法都真实实践过,每一篇文章都良心制作过. [学无止 ...
- [LeetCode] Two Sum 两数之和
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
随机推荐
- linux 编程随笔
Linux 命令: 在linux 系统中,所有的命令都是人为编写的程序,如 who 和 ls ,而且绝大多数都是C写的.在Linux 中增加新的命令是很简单的事,把程序的可执行文件放到以下目录就可以了 ...
- 日历的种类(Project)
<Project2016 企业项目管理实践>张会斌 董方好 编著 日历有三种:标准日历.24小时日历和夜班日历. 设置的位置在[项目]>[属性]>[更改工作时间]>[ ...
- 『与善仁』Appium基础 — 25、APP模拟手势高级操作
目录 1.手指轻敲操作 2.手指按下和抬起操作 3.等待操作 4.手指长按操作 5.手指移动操作 6.综合练习 APP模拟手势的动作都被封装在TouchAction类中,TouchAction是App ...
- CF102B Sum of Digits 题解
Content 给定一个数 \(n\),每次操作可以将 \(n\) 变成 \(n\) 各位数之和.问你几次操作之后可以将 \(n\) 变为一位数. 数据范围:\(1\leqslant n\leqsla ...
- curl英文直译
文档概述 比较表 curl手册页 常见问题 HTTP脚本编写 mk-ca-bundle 教程 curl / 文件 / 工具文档 /手册页 curl.1手册页 相关: 手动 常见问题解答 HTTP脚本 ...
- .Net Core 项目发布在IIS上 访问404 问题对应
对策: 1.进入线程池画面,将当前程序的线程池设为"无托管代码" 2.修改配置文件 Web.config,加上配置 原因: 因为.NetCore 5.0 自带集成了Swag ...
- 10-2 bonding
创建bonding设备的配置文件 centos8 /etc/sysconfig/network-scripts/ifcfg-bond0 NAME=bond0 TYPE=bond DEVICE=bond ...
- SQL注入绕过
空格字符绕过 %09 TAB建(水平) %0a 新建一行,换行 %0b TAB建(垂直) %0c 新的一页 %0d return 功能 %a0 空格 %00 /**/ /*!*/./*!50009*/ ...
- JAVA验证身份证号码是否正确
package com.IdCard; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.D ...
- JAVA获取多个经纬度的中心点
import java.util.LinkedList; public class Test1 { /** * 位置实体类,根据自己的来即可 */ static class Position{ /** ...