268. Missing Number
Easy
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Input: [3,0,1] Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
package leetcode.easy; public class MissingNumber { public int missingNumber1(int[] nums) { java.util.Arrays.sort(nums); // Ensure that n is at the last index if (nums[nums.length - 1] != nums.length) { return nums.length; } // Ensure that 0 is at the first index else if (nums[0] != 0) { return 0; } // If we get here, then the missing number is on the range (0, n) for (int i = 1; i < nums.length; i++) { int expectedNum = nums[i - 1] + 1; if (nums[i] != expectedNum) { return expectedNum; } } // Array was not missing any numbers return -1; } public int missingNumber2(int[] nums) { java.util.Set<Integer> numSet = new java.util.HashSet<Integer>(); for (int num : nums) { numSet.add(num); } int expectedNumCount = nums.length + 1; for (int number = 0; number < expectedNumCount; number++) { if (!numSet.contains(number)) { return number; } } return -1; } public int missingNumber3(int[] nums) { int missing = nums.length; for (int i = 0; i < nums.length; i++) { missing ^= i ^ nums[i]; } return missing; } public int missingNumber4(int[] nums) { int expectedSum = nums.length * (nums.length + 1) / 2; int actualSum = 0; for (int num : nums) { actualSum += num; } return expectedSum - actualSum; } @org.junit.Test public void test1() { int[] nums1 = { 3, 0, 1 }; int[] nums2 = { 9, 6, 4, 2, 3, 5, 7, 0, 1 }; System.out.println(missingNumber1(nums1)); System.out.println(missingNumber1(nums2)); } @org.junit.Test public void test2() { int[] nums1 = { 3, 0, 1 }; int[] nums2 = { 9, 6, 4, 2, 3, 5, 7, 0, 1 }; System.out.println(missingNumber2(nums1)); System.out.println(missingNumber2(nums2)); } @org.junit.Test public void test3() { int[] nums1 = { 3, 0, 1 }; int[] nums2 = { 9, 6, 4, 2, 3, 5, 7, 0, 1 }; System.out.println(missingNumber3(nums1)); System.out.println(missingNumber3(nums2)); } @org.junit.Test public void test4() { int[] nums1 = { 3, 0, 1 }; int[] nums2 = { 9, 6, 4, 2, 3, 5, 7, 0, 1 }; System.out.println(missingNumber4(nums1)); System.out.println(missingNumber4(nums2)); } }