LF68.Missing Number I

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LF68.Missing Number I相关的知识,希望对你有一定的参考价值。

Given an integer array of size N - 1, containing all the numbers from 1 to N except one, find the missing number.

Assumptions

The given array is not null, and N >= 1
Examples

A = {2, 1, 4}, the missing number is 3
A = {1, 2, 3}, the missing number is 4
A = {}, the missing number is 1


 1 //time o(n) space o(n)
 2     public int missing_method1(int[] array) {
 3         // Write your solution here
 4         //corner case
 5         if (array == null){
 6             return -1 ;
 7         }
 8         // since we know for sure there is one number missing from array
 9         int size = array.length ;
10         //1: put for 1 to size into hashset
11         Set<Integer> dic = new HashSet<>(size) ;
12         for (int i = 0 ; i <size ; i++){
13             dic.add(array[i]);
14         }
15         //2: and then loop through the array and cross check with the dic
16         for (int i = 1; i <= size +1 ; i++) {
17             if (!dic.contains(i)){
18                 return i;
19             }
20         }
21         return -1 ;
22     }
23 
24     // time o(n) space o(1)
25     public int missing_method2(int[] array) {
26         // Write your solution here
27         //corner case
28         if (array == null){
29             return -1 ;
30         }
31         int size = array.length ;
32         int sum = 0 ;
33         for (int i = 0 ; i <size ; i++){
34             sum += array[i] ;
35         }
36         //2: and then loop through the array and cross check with the dic
37         int total = 0 ;
38         for (int i = 1; i <= size +1 ; i++) {
39             total += i ;
40         }
41         return total - sum ;
42     }
43 
44     //todo: xor bit operation method save for later

 

以上是关于LF68.Missing Number I的主要内容,如果未能解决你的问题,请参考以下文章

LF.33.number Of Nodes

LF.26.Kth Smallest Number In Sorted Matrix

代码片段:Shell脚本实现重复执行和多进程

新手一个.c语言代码该怎么 改?

1104 Sum of Number Segments(二刷)

[Grid Layout] Use auto-fill and auto-fit if the number of repeated grid tracks is not to be def(代码片段