[GeeksForGeeks] Find the smallest missing number

Given a sorted array of n distinct integers where each integer is in the range from 0 to m - 1 and m > n. Find the smallest number that is missing from the array. 

 

Analysis:

Solution 1. O(n), linear scan;

Solution 2. O(log n), binary search: if arr[mid] > mid, then the first missing number must be in the left half; otherwise, it must be in the right half. 

 

Solution 2 does not work if the given array can have duplicated integers.

 

 1 public class SmallestMissingNumber {
 2     public static int SmallestMissingNumberLinear(int[] arr) {
 3         int idx = 0;
 4         if(arr[idx] != idx) {
 5             return idx;
 6         }
 7         while(idx < arr.length - 1) {
 8             if(arr[idx + 1] - arr[idx] > 1) {
 9                 break;
10             }
11             idx++;
12         }
13         return arr[idx] + 1;
14     }
15     public static int SmallestMissingNumberBinary(int[] arr) {
16         int start = 0, end = arr.length - 1;
17         if(arr[start] != start) {
18             return start;
19         }
20         while(end >= start) {
21             int mid = start + (end - start) / 2;        
22             if(arr[mid] > mid) {
23                 end = mid - 1;
24             }
25             else {
26                 start = mid + 1;
27             }
28         }
29         return start;
30     }
31     public static int SmallestMissingNumberWithDuplicates(int[] arr) {
32         int idx = 0;
33         if(arr[idx] != idx) {
34             return idx;
35         }
36         int nextVal = 1;
37         for(idx = 1; idx < arr.length; idx++) {
38             if(arr[idx] == arr[idx - 1]) {
39                 continue;
40             }
41             else if(arr[idx] == nextVal) {
42                 nextVal++;
43             }
44             else {
45                 break;
46             }
47         }
48         return nextVal;
49     }
50     public static void main(String[] args) {
51         int[] arr1 = {0, 1, 2, 6, 9};
52         System.out.println(SmallestMissingNumberBinary(arr1));
53         int[] arr2 = {4, 5, 10, 11};
54         System.out.println(SmallestMissingNumberBinary(arr2));        
55         int[] arr3 = {0, 1, 2, 3, 4};
56         System.out.println(SmallestMissingNumberBinary(arr3));    
57         int[] arr4 = {1, 2, 3, 4};
58         System.out.println(SmallestMissingNumberBinary(arr4));    
59         int[] arr5 = {0, 0, 0, 0};
60         System.out.println(SmallestMissingNumberWithDuplicates(arr5));
61         int[] arr6 = {0, 1, 2, 3, 3};
62         System.out.println(SmallestMissingNumberWithDuplicates(arr6));        
63     }
64 }

 

posted @ 2017-12-05 12:52  Review->Improve  阅读(185)  评论(0编辑  收藏  举报