?LeetCode刷題實(shí)戰(zhàn)268:丟失的數(shù)字
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?丟失的數(shù)字,我們先來看題面:https://leetcode-cn.com/problems/missing-number/
給定一個(gè)包含 [0, n] 中 n 個(gè)數(shù)的數(shù)組 nums ,找出 [0, n] 這個(gè)范圍內(nèi)沒有出現(xiàn)在數(shù)組中的那個(gè)數(shù)。進(jìn)階:你能否實(shí)現(xiàn)線性時(shí)間復(fù)雜度、僅使用額外常數(shù)空間的算法解決此問題?Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
示例
示例 1:
輸入:nums = [3,0,1]
輸出:2
解釋:n = 3,因?yàn)橛?3 個(gè)數(shù)字,所以所有的數(shù)字都在范圍 [0,3] 內(nèi)。2 是丟失的數(shù)字,因?yàn)樗鼪]有出現(xiàn)在 nums 中。
示例 2:
輸入:nums = [0,1]
輸出:2
解釋:n = 2,因?yàn)橛?2 個(gè)數(shù)字,所以所有的數(shù)字都在范圍 [0,2] 內(nèi)。2 是丟失的數(shù)字,因?yàn)樗鼪]有出現(xiàn)在 nums 中。
示例 3:
輸入:nums = [9,6,4,2,3,5,7,0,1]
輸出:8
解釋:n = 9,因?yàn)橛?9 個(gè)數(shù)字,所以所有的數(shù)字都在范圍 [0,9] 內(nèi)。8 是丟失的數(shù)字,因?yàn)樗鼪]有出現(xiàn)在 nums 中。
示例 4:
輸入:nums = [0]
輸出:1
解釋:n = 1,因?yàn)橛?1 個(gè)數(shù)字,所以所有的數(shù)字都在范圍 [0,1] 內(nèi)。1 是丟失的數(shù)字,因?yàn)樗鼪]有出現(xiàn)在 nums 中。
解題
這里利用nums中的所有數(shù)字都獨(dú)一無二這個(gè)條件,使用異或運(yùn)算來對(duì)數(shù)組index及值進(jìn)行運(yùn)算,遍歷完得出的結(jié)果就是丟失的數(shù)字。
class?Solution?{
????public?int?missingNumber(int[] nums)?{
????????int?result = nums.length;
????????for?(int?i = 0; i < nums.length; ++i){
????????????result ^= nums[i];
????????????result ^= i;
????????}
????????return?result;
????}
}
好了,今天的文章就到這里,如果覺得有所收獲,請(qǐng)順手點(diǎn)個(gè)在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動(dòng)力 。
上期推文:
LeetCode1-260題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)261:以圖判樹
LeetCode刷題實(shí)戰(zhàn)262:行程和用戶LeetCode刷題實(shí)戰(zhàn)263:丑數(shù)
LeetCode刷題實(shí)戰(zhàn)264:丑數(shù) IILeetCode刷題實(shí)戰(zhàn)265:粉刷房子II
LeetCode刷題實(shí)戰(zhàn)266:回文排列
LeetCode刷題實(shí)戰(zhàn)267:回文排列II
