题目:
An array of integer of size N-1, all the elements are from range[1,N], one is missing, find it.
代码:
import java.util.*;
class Test{
public static void main(String[] args){
Solution sol = new Solution();
int[] A = {1, 2, 3, 5, 6, 8, 4};
System.out.println(sol.getMis(A));
System.out.println(sol.getMis2(A));
}
}
class Solution {
//O(n) + O(n), index法
public int getMis(int[] A){
boolean[] bul = new boolean[A.length+2];
for(int data : A)
bul[data] = true;
for(int i=1; i<=bul.length; i++)
if(!bul[i]) return i;
return -1;
}
//O(n) + O(0), 两和相减法,有可能会overflow
public int getMis2(int[] A){
int sum = 0, exp = (2+A.length)*(A.length+1)/2;
for(int i=0; i<A.length; i++)
sum += A[i];
return exp - sum;
}
}
总结:
两种方法,还有一种XOR的方法,没有搞明白。