您的位置:首页 > 其它

LeetCode 268

2016-05-10 19:12 239 查看
Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?

/*************************************************************************
> File Name: LeetCode268.c
> Author: Juntaran
> Mail: Jacinthmail@gmail.com
> Created Time: Tue 10 May 2016 06:19:13 PM CST
************************************************************************/

/*************************************************************************

Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?

************************************************************************/

#include <stdio.h>

/* 通用方法 */
int missingNumber( int* nums, int numsSize )
{
int sum = ( 0 + numsSize) * (numsSize+1) / 2;
int ret = 0;
int i;
for( i=0; i<numsSize; i++ )
{
ret += nums[i];
}
ret = sum - ret;
return ret;
}

/* 如果数据是从0递增的话可以使用以下方法 */
/* 测试用例包含不是纯从0递增数组,所以此方法LeetCode不通过 */
int missingNumber2( int* nums, int numsSize )
{
int i;

for( i=0; i<numsSize; i++ )
{
if( i != nums[i] )
{
return i;
}
}
return numsSize;
}

int main()
{
int nums[] = { 0, 1, 3 };
int numsSize = 3;

int ret = missingNumber2( nums, numsSize );
printf("%d\n", ret);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: