My answer:
class Solution { public int missingNumber(int[] nums) { if (nums == null || nums.length < 1) { return 0; } int n = nums.length; int expectedSum = n * (n + 1) / 2; int actualSum = 0; for (int i = 0; i < n; i++) { actualSum += nums[i]; } return expectedSum - actualSum; } }
Interesting solution: XOR. Do XOR for each value of array with 0....n, i.e. array index + nums.length.
The result number is the missing one.
Solution is from the article of this question: https://leetcode.com/articles/missing-number/
Because we know that
nums
contains numbers and that it is missing exactly one number on the range , we know that definitely replaces the missing number in nums
. Therefore, if we initialize an integer to and XOR it with every index and value, we will be left with the missing number. Consider the following example (the values have been sorted for intuitive convenience, but need not be):Index | 0 | 1 | 2 | 3 |
---|---|---|---|---|
Value | 0 | 1 | 3 | 4 |
class Solution { public int missingNumber(int[] nums) { int missing = nums.length; for (int i = 0; i < nums.length; i++) { missing ^= i ^ nums[i]; } return missing; } }
No comments:
Post a Comment