Find the missing numbers

Question:

Design and implement an algorithm (C++ function) that, given an array of integers 0 to 2n-1 with two values missing, determines (and displays) the two missing integers. For example, if n is 3, the given integers might be {0,1,3,4,5,7}, so the output would be 2 and 6.

Note that the given integers are in ordered. You may assume there are no duplicate values in the array.

What is the runtime of your algorithm? What is the memory requirement of your algorithm?


test IDE: Microsoft Visual Studio 2005

test OS:Microsoft Windows 7

The code as following may solve this problem:

// MissingNumber.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <cstdio>

int _tmain(int argc, _TCHAR* argv[])
{
	int nCount;
	printf("Input N:");
	scanf("%d", &nCount);
	nCount *= 2;
	int iComp =0;
	int *pData = new int[nCount];
	printf("Input numbers:");
	for(int i = 0;i < nCount; ++i)
	{
		scanf("%d", &pData[i]);
	}
	const int MAX_NUM = nCount + 1;
	printf("The missing numbers are:");
        // note the loop criterion, it can help you to work till the upbound
        for(int i = 0;i < nCount || iComp <= MAX_NUM;) 
        {
                if (pData[i] == iComp)
                {
                        ++iComp;
                        ++i;
                }
                else
                {
                        printf("%d ", iComp);
                        ++iComp;
                }
        }
        return 0;
}

Analysis:The runtime complexity is O(n) and the memory requirement is O(1).

Thinking:

What if the given integers are in any order ?

A resolution may work out to the thinking: You can use quick sort before finding the missing integers.


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值