Find Missing Number on Array
// 代码是从eclipse直接copy过来的 请大家见谅 ," 一个数组找到丢失的那个数 " // BitSet的使用 https://www.cnblogs.com/xupengzhang/p/7966755.html
import java.util.Arrays;
import java.util.BitSet;
/** * * @ClassName: FindMissingNums * @Description: find the numbers missing in Integer array 1 - 100 * @author hepengyu * @date Sep 30, 2018 9:06:01 AM * */ public class FindMissingNums { public static void main(String[] args) { // one missing number printMissageNums(new int [] { 1, 2, 3, 4, 6 }, 6); // duplicate number is OK // printMissageNums(new int[] { 1, 2, 3, 4, 4, 5, 6 }, 8); // only one missing number the second solution
int[] array = new int[] {1,2,3,4,5,7,8,9,10}; int missing = getMissingNumber(array, 10); System.out.printf("Missing number in array %s is %d %n",Arrays.toString(array),missing); } /** * * @Title: printMissageNums
* @Description: print the missing numbers in Integer Arrays
* @param @param arrays
* @param @param count the length of arrays
* @return void return type
* @throws
*/
private static void printMissageNums(int[] arrays, int count) { // missing numbers
int missingNum = count - arrays.length; BitSet bitSet = new BitSet(count); for (int array : arrays) { bitSet.set(array - 1); } System.out.printf("Missing numbers in integer array %s, with total number %d is %n", Arrays.toString(arrays), count); int lastMissingIndex = 0; for (int i = 0; i < missingNum; i++) { lastMissingIndex = bitSet.nextClearBit(lastMissingIndex); System.out.println(++lastMissingIndex); } } /** * * @Title: getMissingNumber * @Description: only one missing number * @param @param number * @param @param count * @param @return
* @return int return type * @throws */ private static int getMissingNumber(int[] number , int count) { int actualSum = 0; int expectedSum = count * (1 + count)/2; for(int array : number) { actualSum += array; } return expectedSum - actualSum; } }
#笔试题目#