[Swift]LeetCode268. 缺失数字 | Missing Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9756490.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。

示例 1:

输入: [3,0,1]
输出: 2

示例 2:

输入: [9,6,4,2,3,5,7,0,1]
输出: 8

说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?


 1 class Solution {
 2     func missingNumber(_ nums: [Int]) -> Int {
 3         //利用异或运算,将数组全体内容与0~n进行异或,
 4         //根据异或运算的性质可知最后结果为缺少的那个数字。
 5         var result:Int = nums.count
 6         for i in 0..<nums.count
 7         {
 8             result ^= i ^ nums[i]
 9         }
10         return result        
11     }
12 }

28ms

1 class Solution {
2     func missingNumber(_ nums: [Int]) -> Int {
3         var h = (nums.count+1)*nums.count/2
4         for i in 0..<nums.count {
5            h -= nums[i]
6         }
7         return h
8     }
9 }

24ms

 1 class Solution {
 2     func missingNumber(_ nums: [Int]) -> Int {
 3         var sum = 0 
 4         var max = 0
 5         var i = 0
 6         while i < nums.count {
 7             max = max + i
 8             sum = sum + nums[i]
 9             i = i + 1
10         }
11         return max - sum + i
12     }
13 }

32ms:

求出从0~n的累加和,减去数组整体的和,那么由于数组内每个数字不相同,其差就是缺少的那个数字

 1 class Solution {
 2     func missingNumber(_ nums: [Int]) -> Int {
 3         let count = nums.count
 4         var sum = count + (count * (count - 1)) / 2
 5         
 6         for i in 0..<count {
 7             sum -= nums[i]
 8         }
 9         return sum
10     }
11 }

 

转载于:https://www.cnblogs.com/strengthen/p/9756490.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值