[LeetCode] 268. Missing Number
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 1:
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.
Example 2:
Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
Constraints:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
- All the numbers of
nums
are unique.
Follow up: Could you implement a solution using only O(1)
extra space complexity and O(n)
runtime complexity?
丢失的数字。
给定一个包含 [0, n]
中 n
个数的数组 nums
,找出 [0, n]
这个范围内没有出现在数组中的那个数。
这道题我提供三种思路
1. 数学方法
如果数组是完整的,整个数组的和应该是(首项+末项)x 项数 / 2 →设为A
事实情况的加和设为B,A - B即可得到失去的数字,代码如下
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var missingNumber = function(nums) { 6 let res = 0; 7 let len = nums.length; 8 let expected = ((1 + len) * len) / 2; 9 let calculated = 0; 10 for (let i = 0; i < nums.length; i++) { 11 calculated += nums[i]; 12 } 13 res = expected - calculated; 14 return res; 15 };
Java实现
1 class Solution { 2 public int missingNumber(int[] nums) { 3 int n = nums.length; 4 int total = n * (n + 1) / 2; 5 int sum = 0; 6 for (int num : nums) { 7 sum += num; 8 } 9 return total - sum; 10 } 11 }
2. 位运算方法
因为数组长度是n,数组里面的数字是0-n范围内的,也许我们可以将数组num[i]和他们的下标做一个关联,由此想到了位运算的做法。例子,如果数组是排序好的(没排序也行,因为位运算遵循交换律,此处为解释方便)
每个数字num[i]和下标i做异或运算XOR,若两者相同,结果为0。根据题意,应该最后就剩下某个数字M= num[i]。M和0再做异或运算,还是M。所以M就是那个失踪的数字。代码如下,
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var missingNumber = function(nums) { 6 let res = nums.length; 7 for (let i = 0; i < nums.length; i++) { 8 res ^= i ^ nums[i]; 9 } 10 return res; 11 };
Java实现
1 class Solution { 2 public int missingNumber(int[] nums) { 3 int res = nums.length; 4 for (int i = 0; i < nums.length; i++) { 5 res ^= i ^ nums[i]; 6 } 7 return res; 8 } 9 }
3. 桶排序bucket sort,还是将数字放到它该去的位置上,这样使得数组有序。第二遍扫描的时候就知道哪个数字是缺失的了。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int missingNumber(int[] nums) { 3 for (int i = 0; i < nums.length; i++) { 4 while (nums[i] >= 0 && nums[i] < nums.length && nums[i] != nums[nums[i]]) { 5 int temp = nums[nums[i]]; 6 nums[nums[i]] = nums[i]; 7 nums[i] = temp; 8 } 9 } 10 11 for (int i = 0; i < nums.length; i++) { 12 if (nums[i] != i) { 13 return i; 14 } 15 } 16 return nums.length; 17 } 18 }
相关题目
442. Find All Duplicates in an Array