LeetCode 【1】 Two Sum --001
5月箴言
住进布达拉宫,我是雪域最大的王。流浪在拉萨街头,我是世间最美的情郎。—— 仓央嘉措
从本周起每周研究一个算法,并以swift实现之
001 -- Two Sum (两数之和)
题干英文版:
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].
题干中文版:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
目前想到两种解法:
方法一、暴力查询,两边for循环数组,计算是否存在等于目标值的,存在就返回对应的坐标,不存在 返回-1,-1
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
guard nums.count > 1 else{
return [-1,-1]
}
for i in 0..<nums.count-1{
var j = i+1
for j in j..<nums.count{
if(nums[i] + nums[j] == target){
return [i,j]
}
}
}
return [-1,-1]
}
}
运行时间和所占内存:
Runtime: 472 ms, faster than 24.78% of Swift online submissions for Two Sum.
Memory Usage: 21 MB, less than 5.12% of Swift online submissions for Two Sum.
复杂度分析:
时间复杂度 O(n^2)。
方法二:利用字典,因为字典或者集合经常使用的原因是因为查询的时间复杂度是O(1),原因是一般字典和集合会要求他们的key都必须遵守Hashable协议
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
guard nums.count > 1 else{
return [-1,-1]
}
var dict:[Int:Int] = [:]
for i in 0..<nums.count {
let item = target-nums[i]
if let found = dict[item]{
return [found , i]
}else{
dict[(nums[i])] = i
}
}
return [-1, -1]
}
}
时间和空间复杂度:
Runtime: 48 ms, faster than 46.77% of Swift online submissions for Two Sum.
Memory Usage: 21.1 MB, less than 5.12% of Swift online submissions for Two Sum.
复杂度分析:
时间复杂度 O(n)。
可以看出方法二运行时间变为方法一的约1/10,空间复杂度区别不大。
关于时间复杂度和空间复杂度的概念,目前尚不是非常清晰(在之后会一步一步改进的)。
167 -- Two Sum II - Input array is sorted
题干英文版:
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
题干中文版:
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
- 返回的下标值(index1 和 index2)不是从零开始的。
- 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
目前想到的实现思路是根据001的两数之和,可知加入到字典中的数据的索引是从小到大的,因此我们可以知道的是字典中已经存在的索引应该是小于后来遍历到的,
因此其实现如下:
class Solution {
func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
guard numbers.count > 1 else{
return []
}
//因为先加到字典中的肯定是数组靠前的下标
var dict:[Int:Int] = [:]
for i in 0..<numbers.count {
let item = target-numbers[i]
if let found = dict[item]{
return [found + 1,i + 1]
}else{
dict[(numbers[i])] = i
}
}
return []
}
}
运行时间和内存
Runtime: 28 ms, faster than 100.00% of Swift online submissions for Two Sum II - Input array is sorted.
Memory Usage: 21.1 MB, less than 5.09% of Swift online submissions for Two Sum II - Input array is sorted.
关于算法的实现目前的思路:
1、先实现,用现在经常使用到的数据结构去实现,复杂什么也没关系,最关键是实现它
2、考虑耗时,内存消耗
不要忘了安全校验:诸如判空,特殊处理等。
下期code
有缘看到的亲们:文中若有不对之处,还请劳驾之处,谢谢!
LeetCode 【1】 Two Sum --001的更多相关文章
- LeetCode: 【L4】N-Queens 解题报告
[L4]N-Queens 解题报告 N-Queens Total Accepted: 16418 Total Submissions: 63309 My Submissions The n-queen ...
- 【LibreOJ】【LOJ】#6220. sum
[题意]对于n个数,找出一些数使得它们的和能被n整除,输出任意一组方案,n<=10^6. [算法]构造/结论 [题解]引用自:http://www.cnblogs.com/Sakits/p/74 ...
- 【Leetcode】【Medium】Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【Leetcode】【Medium】Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- 【Leetcode】【Easy】Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- 【Leetcode】【Medium】Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...
- 【Leetcode】【Medium】Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- LeetCode 【2】 Reverse Integer --007
六月箴言 万物之中,希望最美:最美之物,永不凋零.—— 斯蒂芬·金 第二周算法记录 007 -- Reverse Integer (整数反转) 题干英文版: Given a 32-bit signed ...
- 【转载】Combination Sum
Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...
随机推荐
- Qt编写自定义控件56-波浪曲线
一.前言 波浪曲线控件,其实是之前一个水波进度条控件的一个核心,其实就是利用正弦曲线来生成对应的坐标进行绘制,把这个功能单独提取出来,是为了更详细的研究各种正弦余弦等拓展效果,当时写这个效果的时候,参 ...
- 关于jmeter+ant+jenkins性能自动化将测试结果文件jtl转换成html文件遇到的问题。
1.ant自身缺陷,返回结果中有特殊字符,乱码字符,无法识别,jtl文件转换时报错. 2.jtl文件过大转换成html文件时出现内存溢出. 针对以上情况:可考虑使用BeenShell Sampler: ...
- delphi 根据特殊符号字符获取字符串前或后的字符
function GetBefore(substr, str:string):string; {©Drkb v.3(2007): www.drkb.ru, ®Vit (Vitaly Nevzorov) ...
- mysql创建数据库、表、写数据
mysql> create database ceshi; Query OK, 1 row affected (0.01 sec) 给数据库授权,否则程序时无法连接ceshi数据库的,每次创建一 ...
- charles 批量重复请求/重复发包工具
本文参考:charles 批量请求 重复发包工具/repeat Charles 让你选择一个请求并重复,在测试后端接口的时候非常有用: Charles将请求重新发送到服务器,并将响应显示为新请求. 如 ...
- VLOOKUP函数 from Excel
1.VLOOKUP函数是Excel中的一个纵向查找函数,它与LOOKUP函数和HLOOKUP函数属于一类函数,在工作中都有广泛应用,例如可以用来核对数据,多个表格之间快速导入数据等函数功能.功能是按列 ...
- OWASP TOP 10(OWASP十大应用安全风险)
TOP1-注入 当不受信任的数据作为命令或查询的一部分发送到解释器时,会发生注入漏洞,例如SQL,NoSQL,OS,LDAP注入(轻量目录访问协议),xpath(XPath即为XML路径语言,它是一种 ...
- Npcap.例子(raw tcp syn)
1.来自:winpcap实现syn攻击 - 125096 - CSDN博客.html(https://blog.csdn.net/qq125096885/article/details/5178452 ...
- 创建Webpack 4.X项目
创建基本的webpack4.x项目 运行npm init -y 快速初始化项目 在项目根目录创建src源代码目录和dist产品目录 在 src 目录下创建 index.html 使用 cnpm 安装 ...
- 在vue中使用axios发送post请求,参数方式
由于后台接收的参数格式为FormData格式, 在axios中参数格式默认为, 在传参数前,将原先官方提供的格式 改为如下: axios({ url: '../../../room/listRoomP ...