Given an array containing n distinct numbers taken from
0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums =
Given nums =
[0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
SolutionYour algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Again, similar to other bit manipulation problems, we can use XOR operator. One NOTE about XOR:
1. if A ^ B = C then A = B ^ C, and B = A ^ C,
2. and A^A = 0, 0 ^ A = A,
where ^ is XOR bit operator.
Since nums contains numbers from 0 to n with one number is missing, then if we xor all the numbers in nums with 0 ^ 1 ^ 2 ... ^ n, we will get the number we need to find.
Below is the codes.
I. Java Code
public class Solution { public int missingNumber(int[] nums) { int r = 0; for (int i = 0; i<nums.length; i++){ r ^= i ^ nums[i]; } return r ^ nums.length; } }II. Python Code
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ r = 0 for i in range(len(nums)): r ^= i ^ nums[i] return r ^ len(nums)III. C++ Code
class Solution { public: int missingNumber(vector<int>& nums) { int r = 0; for (int i = 0; i<nums.size(); i++){ r ^= i ^ nums[i]; } return r ^ nums.size(); } };IV. Javascript Code
/** * @param {number[]} nums * @return {number} */ var missingNumber = function(nums) { var r = 0; for(var i = 0; i<nums.length; i++){ r ^= i ^ nums[i]; } return r ^ nums.length; };Appendix A: Other methods
We can use other methods such as Hash Table with O(n) space complexity. We also can get the number by summing up all the elements in the array, the take the difference of n(n+1)/2 and that sum. (NOTE: n(n+1)/2 is the sum of numbers from 0 to n).
No comments:
Post a Comment