LeetCode 268

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?

 1 /*************************************************************************
 2     > File Name: LeetCode268.c
 3     > Author: Juntaran
 4     > Mail: Jacinthmail@gmail.com
 5     > Created Time: Tue 10 May 2016 06:19:13 PM CST
 6  ************************************************************************/
 7 
 8 /*************************************************************************
 9 
10     Missing Number
11     
12     Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, 
13     find the one that is missing from the array.
14 
15     For example,
16     Given nums = [0, 1, 3] return 2.
17 
18     Note:
19     Your algorithm should run in linear runtime complexity. 
20     Could you implement it using only constant extra space complexity?
21 
22  ************************************************************************/
23  
24 #include <stdio.h>
25 
26 /* 通用方法 */
27 int missingNumber( int* nums, int numsSize )
28 {
29     int sum = ( 0 + numsSize) * (numsSize+1) / 2;
30     int ret = 0;
31     int i;
32     for( i=0; i<numsSize; i++ )
33     {
34         ret += nums[i];
35     }
36     ret = sum - ret;
37     return ret;
38 }
39 
40 /* 如果数据是从0递增的话可以使用以下方法 */
41 /* 测试用例包含不是纯从0递增数组,所以此方法LeetCode不通过 */
42 int missingNumber2( int* nums, int numsSize )
43 {
44     int i;
45     
46     for( i=0; i<numsSize; i++ )
47     {
48         if( i != nums[i] )
49         {
50             return i;
51         }
52     }
53     return numsSize;
54 }
55 
56 int main()
57 {
58     int nums[] = { 0, 1, 3 };
59     int numsSize = 3;
60     
61     int ret = missingNumber2( nums, numsSize );
62     printf("%d
", ret);
63 
64     return 0;
65 }
原文地址:https://www.cnblogs.com/Juntaran/p/5479100.html