在数组中查找缺失数字的最快方法

问题描述 投票:67回答:31

我有一个从1到100(包括两者)的数字数组。数组的大小为100.数字随机添加到数组中,但数组中有一个随机空插槽。找到该插槽的最快捷方式是什么,以及插入插槽的数量是多少? Java解决方案更可取。

java arrays algorithm
31个回答
130
投票

你可以在O(n)中做到这一点。迭代数组并计算所有数字的总和。现在,从1到N的自然数之和可以表示为Nx(N+1)/2。在你的情况下N = 100。

Nx(N+1)/2中减去数组的总和,其中N = 100。

这是缺少的数字。可以在迭代期间检测空时隙,其中计算总和。

// will be the sum of the numbers in the array.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++)
{
    if (arr[i] == 0)
    {
         idx = i; 
    }
    else 
    {
         sum += arr[i];
    }
}

// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;

System.out.println("missing number is: " + (total - sum) + " at index " + idx);

2
投票

这是c#但它应该非常接近你需要的东西:

int findmissing(int arr[], int n)
{
    long bloom=0;
    int i;
    for(i=0; i<;n; i++)bloom+=1>>arr[i];
    for(i=1; i<=n, (bloom<<i & 1); i++);
    return i;
}

2
投票

例如,在面试时间,不涉及重复添加或n(n + 1)/ 2公式的解决方案并不适合您。

您必须使用4个整数(32位)或2个整数(64位)的数组。使用(-1&〜(1 << 31))>> 3.初始化最后一个int(高于100的位设置为1)或者可以使用for循环将位设置为100以上。

  1. 遍历数字数组并将1设置为与数字对应的位位置(例如,71将在从第7位开始的第3个int上设置为从左到右)
  2. 通过4个整数(32位版本)或2个整数(64位版本)的数组
int sumNumbers = 0;
int emptySlotIndex = -1;

for (int i = 0; i < arr.length; i++)
{
  if (arr[i] == 0)
    emptySlotIndex = i;
  sumNumbers += arr[i];
}

int missingNumber = 5050 - sumNumbers;

示例:(32位版本)假设缺少的数字是58.这意味着第二个整数的第26位(从左到右)设置为0。

第一个int是-1(所有位都已设置)所以,我们继续第二个,并将数字32添加到“no”。第二个int与-1不同(未设置位)因此,通过应用NOT(〜)运算符到我们得到的数字64.在幂x处可能的数字是2,我们可以通过使用log on base 2计算x;在这种情况下,我们得到log2(64)= 6 => 32 + 32 - 6 = 58。

希望这可以帮助。


1
投票

我认为最简单也可能是最有效的解决方案是遍历所有条目并使用bitset来记住设置了哪些数字,然后测试0位。 0位的条目是缺少的数字。


1
投票

这不是搜索问题。雇主想知道你是否掌握了校验和。如果你正在寻找多个唯一的整数,你可能需要二进制或for循环或其他什么,但问题规定“一个随机的空槽”。在这种情况下,我们可以使用流总和。条件:“数字被随机添加到数组中”没有更多细节是没有意义的。问题并不是假设数组必须以整数1开始,因此容忍偏移量起始整数。


    public int MissingNumber(int a[])
    {   
        int bits = sizeof(int) * 8;
        int i = 0;
        int no = 0;
        while(a[i] == -1)//this means a[i]'s bits are all set to 1, the numbers is not inside this 32 numbers section
        {
            no += bits;
            i++;
        }
        return no + bits - Math.Log(~a[i], 2);//apply NOT (~) operator to a[i] to invert all bits, and get a number with only one bit set (2 at the power of something)
    }

成功时间:0.18内存:320576信号:0


1
投票

我发现这个美丽的解决方案:

int[] test = {2,3,4,5,6,7,8,9,10, 12,13,14 }; /*get the missing integer*/ int max = test[test.length - 1]; int min = test[0]; int sum = Arrays.stream(test).sum(); int actual = (((max*(max+1))/2)-min+1); //Find: //the missing value System.out.println(actual - sum); //the slot System.out.println(actual - sum - min);

http://javaconceptoftheday.com/java-puzzle-interview-program-find-missing-number-in-an-array/

1
投票
public class MissingNumberInArray
{
    //Method to calculate sum of 'n' numbers

    static int sumOfNnumbers(int n)
    {
        int sum = (n * (n+1))/ 2;

        return sum;
    }

    //Method to calculate sum of all elements of array

    static int sumOfElements(int[] array)
    {
        int sum = 0;

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

        return sum;
    }

    public static void main(String[] args)
    {
        int n = 8;

        int[] a = {1, 4, 5, 3, 7, 8, 6};

        //Step 1

        int sumOfNnumbers = sumOfNnumbers(n);

        //Step 2

        int sumOfElements = sumOfElements(a);

        //Step 3

        int missingNumber = sumOfNnumbers - sumOfElements;

        System.out.println("Missing Number is = "+missingNumber);
    }
}

1
投票

从一系列数字中找出缺失的数字。 IMP指出要记住。

  1. 数组应该排序..
  2. 函数不适用于多个缺失。
  3. 序列必须是AP。 function solution($A) { // code in PHP5.5 $n=count($A); for($i=1;$i<=$n;$i++) { if(!in_array($i,$A)) { return (int)$i; } } }

0
投票

该程序发现缺少数字

    public int execute2(int[] array) {
    int diff = Math.min(array[1]-array[0], array[2]-array[1]);
    int min = 0, max = arr.length-1;
    boolean missingNum = true;
    while(min<max) {
        int mid = (min + max) >>> 1;
        int leftDiff = array[mid] - array[min];
        if(leftDiff > diff * (mid - min)) {
            if(mid-min == 1)
                return (array[mid] + array[min])/2;
            max = mid;
            missingNum = false;
            continue;
        }
        int rightDiff = array[max] - array[mid];
        if(rightDiff > diff * (max - mid)) {
            if(max-mid == 1)
                return (array[max] + array[mid])/2;
            min = mid;
            missingNum = false;
            continue;
        }
        if(missingNum)
            break;
    }
    return -1;
}

0
投票

您可以做的一件事是使用快速排序对数字进行排序。然后使用for循环遍历排序数组,从1到100.在每次迭代中,将数组中的数字与for循环增量进行比较,如果发现索引增量与数组值不同,则找到了您丢失的号码以及缺失的索引。


0
投票

以下是查找给定数组中所有缺失数字的解决方案:

<?php
$arr_num=array("1","2","3","5","6");
$n=count($arr_num);
for($i=1;$i<=$n;$i++)
{       
      if(!in_array($i,$arr_num))
      {
      array_push($arr_num,$i);print_r($arr_num);exit;
      }

}
?>

24
投票

我们可以使用比求和更安全的XOR运算,因为在编程语言中如果给定的输入很大,它可能会溢出并可能给出错误的答案。

在去解决方案之前,知道A xor A = 0。因此,如果我们将两个相同的数字相异,则该值为0。

现在,对阵列中存在的元素进行异或[1..n]取消相同的数字。所以最后我们会得到丢失的号码。

// Assuming that the array contains 99 distinct integers between 1..99
// and empty slot value is zero
int XOR = 0;
for(int i=0; i<100; i++) {
    if (ARRAY[i] != 0)
        XOR ^= ARRAY[i];
    XOR ^= (i + 1);
}
return XOR;

0
投票

假设你有n为8,我们的数字范围从0到8这个例子我们可以表示所有9个数字的二进制表示如下0000 0001 0010 0011 0100 0101 0110 0111 1000

在上面的序列中没有缺失的数字,并且在每列中零和1的数量匹配,但是一旦你删除1个值就让我们说3我们在列的0和1的数量上得到平衡。如果列中的0的数量<= 1的数量,我们缺少的数字在该位的位置将为0,否则如果0的数量>该位的位数为1,则该位的位置将为1我们测试从左到右的位,在每次迭代时,我们丢弃一半数组用于测试下一位,奇数数组值或偶数数组值在每次迭代时被丢弃,具体取决于我们缺少哪一位上。

以下解决方案使用C ++

public class FindMissingNumbers {

/**
 * The function prints all the missing numbers from "n" consecutive numbers.
 * The number of missing numbers is not given and all the numbers in the
 * given array are assumed to be unique.
 * 
 * A similar approach can be used to find all no-unique/ unique numbers from
 * the given array
 * 
 * @param n
 *            total count of numbers in the sequence
 * @param numbers
 *            is an unsorted array of all the numbers from 1 - n with some
 *            numbers missing.
 * 
 */
public static void findMissingNumbers(int n, int[] numbers) {

    if (n < 1) {
        return;
    }

    byte[] bytes = new byte[n / 8];
    int countOfMissingNumbers = n - numbers.length;

    if (countOfMissingNumbers == 0) {
        return;
    }

    for (int currentNumber : numbers) {

        int byteIndex = (currentNumber - 1) / 8;
        int bit = (currentNumber - byteIndex * 8) - 1;
        // Update the "bit" in bytes[byteIndex]
        int mask = 1 << bit;
        bytes[byteIndex] |= mask;
    }
    for (int index = 0; index < bytes.length - 2; index++) {
        if (bytes[index] != -128) {
            for (int i = 0; i < 8; i++) {
                if ((bytes[index] >> i & 1) == 0) {
                    System.out.println("Missing number: " + ((index * 8) + i + 1));
                }
            }
        }
    }
    // Last byte
    int loopTill = n % 8 == 0 ? 8 : n % 8;
    for (int index = 0; index < loopTill; index++) {
        if ((bytes[bytes.length - 1] >> index & 1) == 0) {
            System.out.println("Missing number: " + (((bytes.length - 1) * 8) + index + 1));
        }
    }

}

public static void main(String[] args) {

    List<Integer> arrayList = new ArrayList<Integer>();
    int n = 128;
    int m = 5;
    for (int i = 1; i <= n; i++) {
        arrayList.add(i);
    }
    Collections.shuffle(arrayList);
    for (int i = 1; i <= 5; i++) {
        System.out.println("Removing:" + arrayList.remove(i));
    }
    int[] array = new int[n - m];
    for (int i = 0; i < (n - m); i++) {
        array[i] = arrayList.get(i);
    }
    System.out.println("Array is: " + Arrays.toString(array));

    findMissingNumbers(n, array);
}

}

在每次迭代中,我们将输入空间减少2,即N,N / 2,N / 4 ... = O(log N),空间为O(N)

int getMissingNumber(vector<int>* input, int bitPos, const int startRange)
{
    vector<int> zeros;
    vector<int> ones;
    int missingNumber=0;

    //base case, assume empty array indicating start value of range is missing
    if(input->size() == 0)
        return startRange;

    //if the bit position being tested is 0 add to the zero's vector
    //otherwise to the ones vector
    for(unsigned int i = 0; i<input->size(); i++)
    {
        int value = input->at(i);
        if(getBit(value, bitPos) == 0)
            zeros.push_back(value);
        else
            ones.push_back(value);
    }

    //throw away either the odd or even numbers and test
    //the next bit position, build the missing number
    //from right to left
    if(zeros.size() <= ones.size())
    {
        //missing number is even
        missingNumber = getMissingNumber(&zeros, bitPos+1, startRange);
        missingNumber = (missingNumber << 1) | 0;
    }
    else
    {
        //missing number is odd
        missingNumber = getMissingNumber(&ones, bitPos+1, startRange);
        missingNumber = (missingNumber << 1) | 1;
    }

    return missingNumber;
}

0
投票

PHP $ n = 100的解决方案;

//Test cases 
[1] when missing number is range start
[2] when missing number is range end
[3] when missing number is odd
[4] when missing number is even

$n*($n+1)/2 - array_sum($array) = $missing_number 将给出缺失数字的索引


0
投票

========排序数组最简单的解决方案===========

array_search($missing_number)

0
投票

程序占用时间复杂度为O(logn)和空间复杂度O(logn)

public int getMissingNumber(int[] sortedArray)
        {
            int missingNumber = 0;
            int missingNumberIndex=0;
            for (int i = 0; i < sortedArray.length; i++)
            {
                if (sortedArray[i] == 0)
                {
                    missingNumber = (sortedArray[i + 1]) - 1;
                    missingNumberIndex=i;
                    System.out.println("missingNumberIndex: "+missingNumberIndex);
                    break;
                }
            }
            return missingNumber;
        }

0
投票
public class helper1 {

public static void main(String[] args) {


    int a[] = {1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12};


    int k = missing(a, 0, a.length);
    System.out.println(k);
}

public static int missing(int[] a, int f, int l) {


    int mid = (l + f) / 2;

    //if first index reached last then no element found 
    if (a.length - 1 == f) {
        System.out.println("missing not find ");
        return 0;
    }

    //if mid with first found 
    if (mid == f) {
        System.out.println(a[mid] + 1);
        return a[mid] + 1;
    }

    if ((mid + 1) == a[mid])
        return missing(a, mid, l);
    else
        return missing(a, f, mid);

  }
 }

0
投票

使用总和公式,

public class MissingNumber {

public static void main(String[] args) {
     int array[] = {1,2,3,4,6};
     int x1 = getMissingNumber(array,6);
    System.out.println("The Missing number is: "+x1);


}
private static int getMissingNumber(int[] array, int i) {

    int acctualnumber =0;
    int expectednumber = (i*(i+1)/2);

    for (int j : array) {
        acctualnumber = acctualnumber+j;

    }
    System.out.println(acctualnumber);
    System.out.println(expectednumber);
    return expectednumber-acctualnumber;

}
}

参考class Main { // Function to ind missing number static int getMissingNo (int a[], int n) { int i, total; total = (n+1)*(n+2)/2; for ( i = 0; i< n; i++) total -= a[i]; return total; } /* program to test above function */ public static void main(String args[]) { int a[] = {1,2,4,5,6}; int miss = getMissingNo(a,5); System.out.println(miss); } }



-1
投票
simple solution with test data :

class A{

  public static void main(String[] args){
    int[] array = new int[200];
    for(int i=0;i<100;i++){
      if(i != 51){
        array[i] = i;  
      }
    }

    for(int i=100;i<200;i++){
      array[i] = i;  
    }

    int temp = 0;
    for(int i=0;i<200;i++){
      temp ^= array[i];
    }

    System.out.println(temp);
  }
} 

-1
投票

如果数组是随机填充的,那么最好能够以O(n)复杂度进行线性搜索。但是,我们可以通过分割和征服方法将复杂度提高到O(log n),类似于giri指出的快速排序,因为数字是按升序/降序排列的。


-1
投票

现在我现在对Big O符号太过尖锐但是你也不能做类似的事情(在Java中)

    //Array is shorted and if writing in C/C++ think of XOR implementations in java as follows.
                    int num=-1;
    for (int i=1; i<=100; i++){
        num =2*i;
        if(arr[num]==0){
         System.out.println("index: "+i+" Array position: "+ num);      
         break;
        }
        else if(arr[num-1]==0){
         System.out.println("index: "+i+ " Array position: "+ (num-1)); 
         break;             
        }           
    }// use Rabbit and tortoise race, move the dangling index faster, 
     //learnt from Alogithimica, Ameerpet, hyderbad**

其中number是数组,数字为1-100。从我对这个问题的解读中,它没有说明何时写下缺失的数字。

或者,如果您可以将i + 1的值抛出到另一个数组中并在迭代后将其打印出来。

当然,它可能不遵守时间和空间规则。就像我说的。我必须强烈要求大O.


22
投票

让给定的数组为A,长度为N.让我们假设在给定的数组中,单个空槽用0填充。

我们可以使用许多方法找到解决这个问题的方法,包括Counting sort中使用的算法。但是,就有效的时间和空间使用而言,我们有两种算法。一个主要使用求和,减法和乘法。另一个使用XOR。数学上两种方法都可以正常工作。但是以编程方式,我们需要用主要措施来评估所有算法

  • 限制(如输入值很大(A[1...N])和/或输入值的数量很大(N))
  • 涉及的条件检查数量
  • 涉及的数学运算的数量和类型

这是因为时间和/或硬件(硬件资源限制)和/或软件(操作系统限制,编程语言限制等)等方面的限制。让我们列出并评估每一个的利弊。 。

算法1:

在算法1中,我们有3个实现。

  1. 使用数学公式(1+2+3+...+N=(N(N+1))/2)计算所有数字的总和(包括未知缺失数)。在这里,N=100。计算所有给定数字的总和。从第一个结果中减去第二个结果将给出缺失的数字。 Missing Number = (N(N+1))/2) - (A[1]+A[2]+...+A[100])
  2. 使用数学公式(1+2+3+...+N=(N(N+1))/2)计算所有数字的总和(包括未知缺失数)。在这里,N=100。从该结果中,减去每个给定的数字给出缺失的数字。 Missing Number = (N(N+1))/2)-A[1]-A[2]-...-A[100]Note:即使第二个实现的公式是从第一个派生出来的,从数学的角度来看都是相同的。但是从编程的角度来看两者都是不同的,因为第一个公式比第二个公式更容易出现位溢出(如果给定的数字尽管加法比减法更快,但第二种实现方式减少了由于加入大值而导致比特溢出的可能性(它没有被完全消除,因为在公式中(N+1)存在的可能性非常小)但是两者同样容易因乘法而出现比特溢出。限制是两种实现只有在N(N+1)<=MAXIMUM_NUMBER_VALUE时给出正确的结果。对于第一次实现,附加的限制是它只在Sum of all given numbers<=MAXIMUM_NUMBER_VALUE时给出正确的结果。)
  3. 计算所有数字的总和(这包括未知缺失数)并并行地减去同一循环中的每个给定数字。这消除了乘法引起位溢出的风险,但是通过加法和减法容易出现位溢出。 //ALGORITHM missingNumber = 0; foreach(index from 1 to N) { missingNumber = missingNumber + index; //Since, the empty slot is filled with 0, //this extra condition which is executed for N times is not required. //But for the sake of understanding of algorithm purpose lets put it. if (inputArray[index] != 0) missingNumber = missingNumber - inputArray[index]; }

在编程语言(如C,C ++,Java等)中,如果表示整数数据类型的位数有限,则由于求和,减法和乘法,所有上述实现都容易出现位溢出,从而导致错误的结果在大输入值(A[1...N])和/或大量输入值(N)的情况下。

算法2:

我们可以使用XOR的属性来解决这个问题,而不必担心位溢出的问题。而且XOR比求和更安全,更快。我们知道XOR的性质,两个相同数字的XOR等于0(A XOR A = 0)。如果我们计算从1到N的所有数字的XOR(这包括未知缺失的数字),然后结果,XOR所有给定的数字,公共数字被取消(自A XOR A=0),最后我们得到缺少号码。如果我们没有位溢出问题,我们可以使用求和和基于XOR的算法来获得解决方案。但是,使用XOR的算法比使用求和,减法和乘法的算法更安全,更快速。并且我们可以避免由求和,减法和乘法引起的额外担忧。

在算法1的所有实现中,我们可以使用XOR而不是加法和减法。

让我们假设,qazxsw poi

实施1 => XOR(1...N) = XOR of all numbers from 1 to N

实施2 => Missing Number = XOR(1...N) XOR (A[1] XOR A[2] XOR...XOR A[100])

实施3 =>

Missing Number = XOR(1...N) XOR A[1] XOR A[2] XOR...XOR A[100]

算法2的所有三种实现都可以正常工作(从编程的角度来看也是如此)。一个优化是,类似于

//ALGORITHM
missingNumber = 0;
foreach(index from 1 to N)
{
    missingNumber = missingNumber XOR index;
    //Since, the empty slot is filled with 0,
    //this extra condition which is executed for N times is not required.
    //But for the sake of understanding of algorithm purpose lets put it.
    if (inputArray[index] != 0)
        missingNumber = missingNumber XOR inputArray[index];
}

我们有,

1+2+....+N = (N(N+1))/2

我们可以通过数学归纳证明这一点。因此,我们可以使用此公式来减少XOR运算的数量,而不是通过XOR将所有数字从1到N计算为XOR(1 ... N)的值。

此外,使用上述公式计算XOR(1 ... N)具有两种实现方式。实施明智,计算

1 XOR 2 XOR .... XOR N = {N if REMAINDER(N/4)=0, 1 if REMAINDER(N/4)=1, N+1 if REMAINDER(N/4)=2, 0 if REMAINDER(N/4)=3}

比计算更快

// Thanks to https://a3nm.net/blog/xor.html for this implementation
xor = (n>>1)&1 ^ (((n&1)>0)?1:n)

那么,优化的Java代码是,

xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;

-5
投票

另一个功课问题。顺序搜索是您可以做的最好的。至于Java解决方案,请考虑为读者练习。 :P


17
投票

这是一个亚马逊的采访问题,最初在这里回答:long n = 100; long a[] = new long[n]; //XOR of all numbers from 1 to n // n%4 == 0 ---> n // n%4 == 1 ---> 1 // n%4 == 2 ---> n + 1 // n%4 == 3 ---> 0 //Slower way of implementing the formula // long xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0; //Faster way of implementing the formula // long xor = (n>>1)&1 ^ (((n&1)>0)?1:n); long xor = (n>>1)&1 ^ (((n&1)>0)?1:n); for (long i = 0; i < n; i++) { xor = xor ^ a[i]; } //Missing number System.out.println(xor);

答案如下:

We have numbers from 1 to 52 that are put into a 51 number array, what's the best way to find out which number is missing?

它也在这里写博客:1) Calculate the sum of all numbers stored in the array of size 51. 2) Subtract the sum from (52 * 53)/2 ---- Formula : n * (n + 1) / 2.


9
投票

这是一个简单的程序,用于查找整数数组中缺少的数字

Software Job - Interview Question

6
投票

5050 - (数组中所有值的总和)=缺少数字

ArrayList<Integer> arr = new ArrayList<Integer>();
int a[] = { 1,3,4,5,6,7,10 };
int j = a[0];
for (int i=0;i<a.length;i++)
{
    if (j==a[i])
    {
        j++;
        continue;
    }
    else
    {
        arr.add(j);
        i--;
    j++;
    }
}
System.out.println("missing numbers are ");
for(int r : arr)
{
    System.out.println(" " + r);
}

4
投票

在类似的情况下,数组已经排序,它不包含重复项,只缺少一个数字,可以使用二进制搜索在log(n)时间内找到此缺失的数字。

int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
  if (arr[i] == 0) idx = i; else sum += arr[i];
}
System.out.println("missing number is: " + (5050 - sum) + " at index " + idx);

4
投票

最近我在求职面试中遇到了一个类似的(不完全相同的)问题,我也听到一位朋友在接受采访时被问到完全相同的问题。所以这里是OP问题的答案以及可能会被问到的一些变化。答案示例在Java中给出,因为它声明:

Java解决方案更可取。

变化1:

从1到100(包括两者)的数字数组...数字随机添加到数组中,但数组中有一个随机空插槽

public static int getMissingInt(int[] intArray, int left, int right) {
    if (right == left + 1) return intArray[right] - 1;
    int pivot = left + (right - left) / 2;
    if (intArray[pivot] == intArray[left] + (intArray[right] - intArray[left]) / 2 - (right - left) % 2)
        return getMissingInt(intArray, pivot, right);
    else 
        return getMissingInt(intArray, left, pivot);
}

public static void main(String args[]) {
    int[] array = new int[]{3, 4, 5, 6, 7, 8, 10};
    int missingInt = getMissingInt(array, 0, array.length-1);
    System.out.println(missingInt); //it prints 9
}

说明:此解决方案(此处发布的许多其他解决方案)基于public static int findMissing1(int [] arr){ int sum = 0; for(int n : arr){ sum += n; } return (100*(100+1)/2) - sum; } 的公式,它给出了从1到Triangular number的所有自然数的总和(在这种情况下,n为100)。现在我们知道应该从1到100的总和 - 我们只需要减去给定数组中现有数字的实际总和。

变化2:

从1到n的数字数组(表示最大数字未知)

n

说明:在此解决方案中,由于未给出最大数量 - 我们需要找到它。找到最大数量后 - 逻辑是相同的。

变化3:

从1到n的数字数组(最大数量未知),数组中有两个随机空槽

public static int findMissing2(int [] arr){
    int sum = 0, max = 0;
    for(int n : arr){
        sum += n;
        if(n > max) max = n;
    }
    return (max*(max+1)/2) - sum;
}

说明:在此解决方案中,未给出最大数量(如上所述),但也可能缺少两个数字而不是一个数字。因此,首先我们找到缺失数字的总和 - 使用与以前相同的逻辑。第二个发现缺失金额和最后(可能)缺失数字之间的较小数字 - 以减少不必要的搜索。第三,因为public static int [] findMissing3(int [] arr){ int sum = 0, max = 0, misSum; int [] misNums = {};//empty by default for(int n : arr){ sum += n; if(n > max) max = n; } misSum = (max*(max+1)/2) - sum;//Sum of two missing numbers for(int n = Math.min(misSum, max-1); n > 1; n--){ if(!contains(n, arr)){ misNums = new int[]{n, misSum-n}; break; } } return misNums; } private static boolean contains(int num, int [] arr){ for(int n : arr){ if(n == num)return true; } return false; } s数组(不是集合)没有像JavaindexOf这样的方法,我为该逻辑添加了一个小的可重用方法。第四,当找到第一个缺失的数字时,第二个是从缺失的总和中减去。如果只缺少一个数字,则数组中的第二个数字将为零。

变化4:

从1到n的数字数组(最大数量未知),缺少X(缺失数量未知)

contains

说明:在此解决方案中,与前一个一样,最大数量未知且可能缺少多个数字,但在此变体中,我们不知道可能缺少多少个数字(如果有)。逻辑的开头是相同的 - 找到最大数字。然后我用零初始化另一个数组,在这个数组中,public static ArrayList<Integer> findMissing4(ArrayList<Integer> arr){ int max = 0; ArrayList<Integer> misNums = new ArrayList(); int [] neededNums; for(int n : arr){ if(n > max) max = n; } neededNums = new int[max];//zero for any needed num for(int n : arr){//iterate again neededNums[n == max ? 0 : n]++;//add one - used as index in second array (convert max to zero) } for(int i=neededNums.length-1; i>0; i--){ if(neededNums[i] < 1)misNums.add(i);//if value is zero, than index is a missing number } return misNums; } 表示可能缺少的数字,零表示该数字丢失。因此,原始数组中的每个现有数字都用作索引,其值增加1(最大值转换为零)。

注意

如果您想要其他语言的示例或此问题的其他有趣变体,欢迎您查看我的index存储库以获取Github


3
投票

好吧,使用布隆过滤器。

Interview questions & answers
© www.soinside.com 2019 - 2024. All rights reserved.