解题思路:由于数组中的数字可能不是有序的,所以首先根据规律求出这n+1个数字之和,然后遍历数组并从和中依次减去出现的数字,最后便得出了未选中的数字。
import java.util.*;
public class Solution {
/**
* 找缺失数字
* @param a int整型一维数组 给定的数字串
* @return int整型
*/
public int solve (int[] a) {
// write code here
int sum=0;
if(a!=null){
int n=a.length;
if(n%2==0){
sum=(int)(n*(n+1))/2;
}
else{
sum=(n-1)*(n+1)/2+(n+1)/2;
}
for(int i=0;i<n;i++){
sum=sum-a[i];
}
return sum;
}
return sum;
}
}
京公网安备 11010502036488号