查找数组中缺少的元素

时间:2016-06-02 19:28:04

标签: arrays algorithm performance sorting

数组A包含[0,n-1]范围内的n-1个唯一整数,也就是说,此范围内有一个不在A中的数字。设计一个O(n) - 时间算法用于查找那个数字。除阵列A本身外,您只能使用O(logn)额外空间。

任何人都可以提供帮助吗?

4 个答案:

答案 0 :(得分:2)

从0到n-1的连续整数之和,S = n *(n-1)/ 2;
数组之和,s = calcSum(数组)// O(n)复杂度,需要一个循环

缺少数字= S-s;

复杂性:O(n)
空间复杂度:O(1)

答案 1 :(得分:0)

与其使用求和公式,不如使用XOR运算符在数组中查找丢失的元素。因为求和可能会溢出很大的整数。另一方面,XOR运算符不会导致此类问题。

// C# program to find missing Number
// using xor

using System;

class Program
{
    // Function to find missing number
    static int getMissingElement (int []a, int n)
    {
        int x1 = a[0]; 
        int x2 = 1; 

        /* For xor of all the elements 
        in array */
        for (int i = 1; i < n; i++)
            x1 = x1 ^ a[i];

        /* For xor of all the elements 
        from 1 to n+1 */   
        for (int i = 2; i <= n + 1; i++) // loop to n+1 because including the missing 
 //number the size of the array will increase by 1
            x2 = x2 ^ i;         

        return (x1 ^ x2); // return final xor result
    }

    public static void Main()
    {
        int []a = {1, 2, 4, 5, 6};
        int miss = getMissingElement(a, 5); // size of array is 5
        Console.Write(miss);
    }

}

答案 2 :(得分:0)

def finder(arr1,arr2):
    d={}
    for i in arr1:
        if i in d: 
            d[i]+=1 # if the number is repeated, the value is incremented with 1
        else:
            d[i]=1 # adds all the numbers which are not present in the dictionary
    #print(d)
    for i in arr2:
        if i in d:
            d[i]-=1 # if the number is repeated, the value is decremented with 1
        else:
            d[i]=1 # adds all the numbers which are not present in the dictionary
    #print(d)
    for i in d:
        if d[i]!=0: # The value must not be zero if any number is missing from any of the two arrays, so it will print the missing number(s)
            print(i)
        else:
            return 'No Missing element'



finder(x,y)

答案 3 :(得分:-1)

/**
     * Time Complexity will be 
     * Arrays.sort(A)  = O (n log n)
     * Binary Search O (log n)
     * 
     * Total Time Complexity = O (n log n) + O (log n)
     * 
     * @param A
     * @return
     */
    private static int getMissingElement(int[] A) {
        Arrays.sort(A);

        int low = 0;
        int high = A.length-1;
        int missingElement = 0;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (A[mid] != mid+1) {
                high = mid - 1;
                missingElement = mid +1;
            }
            else {
                low = mid + 1;
            }
        }
        if(missingElement == 0){
            return A.length+1;
        }
        return missingElement;
    }