題目:
Given an array containingn distinct numbers taken
from0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums =[0, 1, 3]
return2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
給定一個包含n個不同數字的數組,從0,1,2,...,n,找到數組中缺失的那個。例如,給定nums = [0,1,3],返回2.
思路:
首先想到的是對這個數組進行遍歷,之前有在Hash Table中遇到Sigle Number,類型差不多,它使用到了異或^,判斷數值是否相同,若不相同則賦值,但在這裏,若不相同則返回這個數。
但當我輸入[0,1]時,輸出結果應該爲2,但我的輸出結果爲3,查看後發現,還需要跟遍歷值進行對比。