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?
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; }
相关文章推荐
- PHP制作验证码
- LeetCode 242
- android 各国语言对应的缩写
- C/C++中的常成员函数
- Java学习笔记(七):内部类、静态类和泛型
- LeetCode 231
- c++作业5
- LeetCode 217
- LeetCode 171
- 同一作用域下函数名(变量名)可以覆盖类、结构体名
- hdu 1181
- POJ 1287 Networking【MST模板题】
- LeetCode 169
- flask笔记:2:Hello World
- Table of Contents - Lombok
- nginx php-fpm 小VPS 优化
- 巧用Singleton(单例)
- 连接oracle数据库
- Linux操作系统几个常用知识点
- CodeForces 165C Another Problem on Strings(组合)