Find Missing Number in Array - Java Code

Find Missing Number in Array - Java Code

Programming Tutorials

5 лет назад

34,259 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Vishnu Vlogger
Vishnu Vlogger - 25.06.2023 10:21

When you given the number 221,223,224 in a array this logic is not working

Ответить
Nitish Kumar Prusty
Nitish Kumar Prusty - 16.05.2023 13:22

import java.util.Arrays;

public class findmissing {
public static void main(String[] args) {
int [] arr = {4,7,8,9,10,5,3,1};
Arrays.sort(arr);
for(int i = 0;i<arr.length-1;i++){
if(arr[i+1] != arr[i] + 1){
System.out.println("the missing Number is " + (arr[i] + 1));
}
}
}
}

Ответить
shubham Ranjan
shubham Ranjan - 03.01.2023 18:55

what if there is 2 numbers is missing???

Ответить
Jagadeesh Baskaran
Jagadeesh Baskaran - 11.06.2022 11:07

is there any other way to do this without using formula?

Ответить
Corvo Attano
Corvo Attano - 11.04.2022 17:29

Easy method
Subscribed :)

Ответить
Here we are
Here we are - 18.01.2022 07:09

What if the numbers are {32,33,34,36}

Ответить
Ambarish Shiva
Ambarish Shiva - 21.11.2021 22:06

Why bro if we add 0 the output change?

Ответить
Mohammed Musaib
Mohammed Musaib - 14.07.2021 21:51

This is also not proper approach to solve this problem becoz here overflows occur

Ответить
Sajramkisho
Sajramkisho - 19.01.2021 18:01

you need to take care of overflow conditions when you use this method of solving .....so better go with XOR method to solve this......

Ответить
kishore maroju
kishore maroju - 05.04.2020 08:23

This solution is not gonna work for all the cases,

int[] array1 = {3,0,1};
missingNumberInTheArray(array1);
}

private static void missingNumberInTheArray(int[] array1) {
int n = array1.length+1;
int sum = (n * (n+1)/2);
System.out.println(sum);

for(int i=0;i<array1.length;i++){
sum=sum-array1[i];
}

System.out.println("finalValue:"+sum);
}

expected output is 2
I am getting 6 as the output


it should be
int sum = (n * (n-1))/2; instead of int sum = (n * (n+1)/2);



Thanks

Ответить
Wiselearning
Wiselearning - 09.02.2020 17:54

Sir why we are taking are.length+1 instead of arr.length

Ответить
sukriti kumari
sukriti kumari - 30.05.2019 13:16

Easy to understand.... thanks

Ответить
Javier Portilla
Javier Portilla - 12.11.2018 05:33

I will like a better explanation, how you define use (n * (n+1))/2 ?

Ответить
Prakash KP
Prakash KP - 21.08.2018 05:12

One of the simplest solution , it works :-)

Ответить