--- title: 'LeetCode 268. Missing Number' disqus: hackmd --- # LeetCode 268. Missing Number ## Description 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. ## Example Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. ## Constraints n == nums.length 1 <= n <= 10^4^ 0 <= nums[i] <= n All the numbers of nums are unique. ## Answer 此題可用for會遞增的概念去當成0~size的疊加,然後減掉nums已有的數,最後仍可找出缺的數值。 ```Cin= int missingNumber(int* nums, int numsSize){ int i=0,ans=numsSize; for(i=0;i<numsSize;i++){ ans = ans - nums[i] + i; } return ans; } ``` 秉持"做兩次XOR會回到原本的數",一開始就將0~size的數全部XOR起來,然後對nums再做一次XOR,即可找出缺的數。 ```Cin= int missingNumber(int* nums, int numsSize){ int i = 0,ans = numsSize; for(i = 0;i<numsSize;i++){ ans = ans^i^nums[i]; } return ans; } ``` ## Link https://leetcode.com/problems/missing-number/ ###### tags: `Leetcode`