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?
Understand the problem:Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Since the problem suggests to use O(n) time complexity and constant space complexity, we can easily think of using the idea of bucket sorting.
For each number, we need to check if i == num[i], if not, we need to swap the number to its corresponding bucket. At last, we iterate the array again and find out the missing number.
There is one corner case to consider: if the array after the bucketing is [0, 1, 2], then the missing number is 3. That is because we have N numbers ranging from 0 to N, the last bucket stores N - 1. So we need to return nums.length.
Code (Java):
public class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
// Step 1: iterate the array and swap according to the buckets
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (num != i && num < nums.length && num != nums[num]) {
swap(nums, i, num);
i--;
}
}
// Step 2: iterate again to find out the missing number
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i) {
return i;
}
}
return nums.length;
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
Spin, wait, and enjoy the thrill. Khelraja offers online roulette with a clean design, smooth gameplay, and that classic casino excitement everyone loves.
ReplyDeleteExperience the heart-pounding tension of a lottery live draw only at KhelRaja. We bring the draw ceremony directly to your screen, ensuring total transparency and an immersive gaming experience. Watching the numbers roll out in real-time adds a layer of authenticity and excitement that static results simply can’t match. Our live streaming features are optimized for all devices, allowing you to witness your potential victory from anywhere. At KhelRaja, we believe in keeping our community engaged and informed, making every live draw an event to remember. Tune in and win big!
ReplyDeleteSecure tax-exempt donations via 80G certificate with NGO Experts. Our legal specialists handle Section 80G registration under Income Tax Act, guaranteeing compliance and 50-100% donor deductions. Effortless process with full documentation aid. Chosen by 500+ NGOs. Start now for enhanced trust and expansion!
ReplyDelete