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


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;
	}

}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 Python实现在给定整数序列中找到和为100的所有数字组合 对于一个有序数组,我们通常采用二分查找的方式来定位某一元素,请编写二分查找的算法,在数组中查找指定元素。 给定一个整数数组A及它的大小n,同时给定要查找的元素val,请返回它在数组中的位置(从0开始),若不存在该元素,返回-1。若该元素出现多次,请返回第一次出现的位置。 如何将一个数字字符串数组转化为数字整数数组? 一个随机类的数字游戏(1-100) 给定一个整数数组ar, 其中只有一个数出现了奇数次数,其他的数都是偶数词,打印这个数。 Leetcode练习(Python):数组类:第53题:给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 在排序数组中查找元素的第一个和最后一个位置(给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。) python计算1-100的整数的和 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字的最小的一个 Leetcode练习(Python):第303题:区域和检索 - 数组不可变:给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM