给定一个 1-100 的整数数组,请找到其中缺少的数字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Arrays;
import java.util.BitSet;
 
/**
 * Java program to find missing elements in a Integer array containing numbers
 * from 1 to 100.
 *
 */
public class MissingNumberInArray {
 
    public static void main(String args[]) {
 
        // one missing number
        printMissingNumber(new int[] { 1, 2, 3, 4, 6 }, 6);
 
        // two missing number
        printMissingNumber(new int[] { 1, 2, 3, 4, 6, 7, 9, 8, 10 }, 10);
 
        // three missing number
        printMissingNumber(new int[] { 1, 2, 3, 4, 6, 9, 8 }, 10);
 
        // four missing number
        printMissingNumber(new int[] { 1, 2, 3, 4, 9, 8 }, 10);
 
        // Only one missing number in array
        int[] iArray = new int[] { 1, 2, 3, 5 };
        int missing = getMissingNumber(iArray, 5);
        System.out.printf("Missing number in array %s is %d %n", Arrays.toString(iArray), missing);
    }
 
    /**
     * A general method to find missing values from an integer array in Java. This
     * method will work even if array has more than one missing element.
     */
    private static void printMissingNumber(int[] numbers, int count) {
        int missingCount = count - numbers.length;
        BitSet bitSet = new BitSet(count);
 
        for (int number : numbers) {
            bitSet.set(number - 1);
        }
 
        System.out.printf("Missing numbers in integer array %s, with total number %d is %n", Arrays.toString(numbers),
                count);
        int lastMissingIndex = 0;
 
        for (int i = 0; i < missingCount; i++) {
            lastMissingIndex = bitSet.nextClearBit(lastMissingIndex);
            System.out.println(++lastMissingIndex);
        }
 
    }
 
    /**
     * Java method to find missing number in array of size n containing numbers from
     * 1 to n only. can be used to find missing elements on integer array of numbers
     * from 1 to 100 or 1 - 1000
     */
    private static int getMissingNumber(int[] numbers, int totalCount) {
        int expectedSum = totalCount * ((totalCount + 1) / 2);
        int actualSum = 0;
        for (int i : numbers) {
            actualSum += i;
        }
 
        return expectedSum - actualSum;
    }
 
}

  

posted @   尐鱼儿  阅读(1066)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示