题目来源:http://www.lintcode.com/zh-cn/problem/find-the-missing-number/
C++版 VS2012测试通过:
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 using namespace std; 5 6 //方法1 7 class Solution { 8 public: 9 /** 10 * @param nums: a vector of integers 11 * @return: an integer 12 */ 13 int findMissing(vector<int> &nums) { 14 // write your code here 15 int n=nums.size()+1; 16 int sum=(n-1)*n/2; 17 for(int i=0;i<nums.size();i++) 18 sum-=nums[i]; 19 return sum; 20 } 21 }; 22 23 //方法2 24 class Solution { 25 public: 26 /** 27 * @param nums: a vector of integers 28 * @return: an integer 29 */ 30 int findMissing(vector<int> &nums) { 31 // write your code here 32 sort(nums.begin(),nums.end()); 33 for(long i=0;i<nums.size();i++) 34 { 35 if(nums[i]!=i) 36 return i; 37 } 38 return nums.size(); 39 } 40 }; 41 42 int main () 43 { 44 int a[5]={0,1,2,3,5}; 45 vector<int> v(a,a+5); 46 Solution s; 47 cout<<s.findMissing(v); 48 }
原文:http://www.cnblogs.com/hslzju/p/5693132.html