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

Reverse Integer

有缘看到的亲们:文中若有不对之处,还请劳驾之处,谢谢!

LeetCode 【1】 Two Sum --001的更多相关文章

  1. LeetCode: 【L4】N-Queens 解题报告

    [L4]N-Queens 解题报告 N-Queens Total Accepted: 16418 Total Submissions: 63309 My Submissions The n-queen ...

  2. 【LibreOJ】【LOJ】#6220. sum

    [题意]对于n个数,找出一些数使得它们的和能被n整除,输出任意一组方案,n<=10^6. [算法]构造/结论 [题解]引用自:http://www.cnblogs.com/Sakits/p/74 ...

  3. 【Leetcode】【Medium】Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  4. 【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 ...

  5. 【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 ...

  6. 【Leetcode】【Medium】Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...

  7. 【Leetcode】【Medium】Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number. The ...

  8. LeetCode 【2】 Reverse Integer --007

    六月箴言 万物之中,希望最美:最美之物,永不凋零.—— 斯蒂芬·金 第二周算法记录 007 -- Reverse Integer (整数反转) 题干英文版: Given a 32-bit signed ...

  9. 【转载】Combination Sum

    Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...

随机推荐

  1. ElasticSearch的Gateway及存储原理

    ES里有一个叫做gateway的东西,今天抽空理一下,前面翻译ES的一篇博文叫做“搜索引擎与时间机器”,既然里面谈到了时间机器,就免不了需要穿越时空的的门咯,I guess,也许gateway这名字就 ...

  2. delphi TClientDatset资料

    第十一章 TClientDataSet 与TTable.TQuery一样,TClientDataSet也是从TDataSet继承下来的,它通常用于多层体系结构的客户端.TClientDataSet最大 ...

  3. Windows server 2008 R2 桌面服务器管理器打开提示:试图引用不存在的令牌

    来源:https://social.technet.microsoft.com/Forums/zh-CN/90f376a3-2b52-46c1-be34-4a2dbf4fdea2/winserver2 ...

  4. 定期删除IIS日志文件

    服务器中由于监控的需要会经常生成很多日志文件,比如IIS日志文件(C:\inetpub\logs\LogFiles),一个稍微有流量的网站,其日志每天可以达到上百兆,这些文件日积月累会严重的占用服务器 ...

  5. iOS技术面试03:Foundation

    是否可以把比较耗时的操作放在NSNotificationCenter中 如果在异步线程发的通知,那么可以执行比较耗时的操作: 如果在主线程发的通知,那么就不可以执行比较耗时的操作 3.Foundati ...

  6. iOS摄像头和相册(转)

    iOS摄像头和相册iOS 获取图片有三种方法1. 直接调用摄像头拍照 2. 从相册中选择 3. 从图库中选择 UIImagePickerController 是系统提供的用来获取图片和视频的接口: 用 ...

  7. 【c# 学习笔记】类实例化

    类中可以定义的成员,包括字段.属性.构造函数.实例方法和析构函数等. 要访问这些实例成员,必须通过类的实例对象来完成.而要得到一个类的实例对象,就必须先声明一个该类类型的变量,然后使用new运算符后跟 ...

  8. 《CNCF × Alibaba云原生技术公开课》知识点自测(一):第一堂“云原生”课

    (单选)1.容器启动后,我会时常 SSH 进入到容器里然后写很多文件.请问这破坏了云原生理念了吗? A. 否   B. 是 (单选)2.云原生架构必须选型 Kubernetes 方案. A. 否  B ...

  9. 人工神经网络反向传播算法(BP算法)证明推导

    为了搞明白这个没少在网上搜,但是结果不尽人意,最后找到了一篇很好很详细的证明过程,摘抄整理为 latex 如下. (原文:https://blog.csdn.net/weixin_41718085/a ...

  10. 记录:larvel Windows 安装

    先安装Composer  不多叙述了 链接: https://pan.baidu.com/s/1sljuImh 密码: qcj3 打开命令窗口 进入你的集成环境 网站根目录下 laravel程序会下载 ...