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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fmdoiqcb-kz.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example 1:github

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:spa

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

示例 2:code

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

說明:
你的算法應具備線性時間複雜度。你可否僅使用額外常數空間來實現?htm


 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 }

28msblog

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 }
相關文章
相關標籤/搜索