Missing Number LeetCode
class Solution {
public int missingNumber(int[] nums) {
int n=nums.length;
int max=0;
int sum=0;
for(int i=0;i<n;i++){
sum=sum+nums[i];
if(nums[i]>max){
max=nums[i];
}
}
int m=max;
int min=0;
boolean flag=false;
for(int i=0;i<n;i++){
if(nums[i]<min){
min=nums[i];
}
}
for(int i=0;i<n;i++){
if(nums[i]==0){
flag=true;
break;
}
else{
flag=false;
}
}
/*System.out.println(" max digit is: "+max);
System.out.println("Tentaive max sum should be: "+(m*(m+1))/2);
System.out.println("Sum of series is: "+sum);
System.out.println("Missing number is : "+((m*(m+1)/2)-sum));*/
if(min==0 && max==0){
return 1;
}
else if(min==0 && max==1){
if(nums.length==1){
return 0;
}
else{
return 2;
}
}
else{
if(flag==true){
int diff=(m*(m+1)/2)-sum;
/*if((diff==0 && nums.length>1) || max==0){
return max+1;
}
else if(diff==0 && nums.length==1){
return 0;
}*/
if(diff==0){
return max+1;
}
else{
return diff;
}
}
else{
return 0;
}
}
}
}
Time:O(N)[LeetCode Time: 0ms faster than 100% ]
Space:O(1)[LeetCode Memory: 39.2MB less than 78.48%]
Thanks For Reading😇.
"Share Further To Increase Knowledge Treasure.😊"
Comments
Post a Comment