码迷,mamicode.com
首页 > 其他好文 > 详细

LF68.Missing Number I

时间:2018-04-05 11:51:42      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:example   pre   eth   public   ace   cas   one   except   case   

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

标签:example   pre   eth   public   ace   cas   one   except   case   

原文地址:https://www.cnblogs.com/davidnyc/p/8721080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!