Give a list of length n+1 with values ranging from 1 to n, where one of the numbers is repeated, and you must find the repeated number. The problem is very similar to looking for missing numbers in an array. In this article, I will share a Java program and algorithm to find repeated numbers between 1 and N numbers.

algorithm

1. Add up all the numbers in the list.

2. Calculate the size n of the unique number in the list and use the arithmetic series formula n*(n+1)/2

3. Subtract the value obtained in step 2 from step 1 and you will get a duplicate number.

Java program

import java.util.List;
import java.util.ArrayList;
public class DuplicateNumberProgram {
    public static void main(String args[]) {
        // Creating the list 
        List<Integer> numbers = new ArrayList<Integer>();
        // Add numbers from 1 to n
        for(int i=1; i < 40; i++) {
            numbers.add(i);
        }
        // adding duplicate number into the list
        numbers.add(35);
        DuplicateNumberProgram obj = new DuplicateNumberProgram();
        int duplicateNumber = obj.getDuplicateNumber(numbers);
        System.out.println(duplicateNumber);
    }
    
    public int findSum(List<Integer> numbers) {
        int sum =0;
        for(int number : numbers) {
            sum += number;
        }
        return sum;
    }
    
    public int getDuplicateNumber(List<Integer> numbers) {
        int n = numbers.size()- 1;
        int total = findSum(numbers);
        int duplicateNum = total - (n * (n+1) /2);
        returnduplicateNum; }}Copy the code

Output:

35

That’s all for today, mention it in the comments, and if you have any questions, look for repeated numbering between 1 and N numbers in Java.

Below is the video clip of the blogger may have nothing to do with the article, I hope you can support it! Thank you for your support!

UP: I only need an hour to show you around.

Ali senior architect explains 2021 latest Java second kill system high performance and high concurrency actual combat project

Java zero basic white watch me this series of videos can do their own actual combat projects! Balance!

2021 latest lntellij IDEA installation, configuration, environment variable teaching

2021 Latest Algorithm training camp: Left God will take you to brush up on LeetCode algorithm (1000 questions) into dachang required algorithm course!

B station first launched the complete collection of SpringCloud Alibaba, a microservice purchased at a huge cost of 12,980