Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array.
Example
Given N = 3 and the array [0, 1, 3], return 2.
Challenge
Do it in-place with O(1) extra memory and O(n) time.
这道题是LeetCode上的原题,请参见我之前的博客Missing Number 丢失的数字。那道题用了两种方法解题,但是LintCode的OJ更加严格,有一个超大的数据集,求和会超过int的范围,所以对于解法一的话需要用long来计算数组之和,其余部分都一样,记得最后把结果转成int即可,参见代码如下:
解法一:
class Solution { public: /** * @param nums: a vector of integers * @return: an integer */ int findMissing(vector<int> &nums) { // write your code here long sum = 0, n = nums.size(); for (auto &a : nums) { sum += a; } return (int)(n * (n + 1) * 0.5 - sum); } };
用位操作Bit Manipulation和之前没有区别,参见代码如下:
解法二:
class Solution { public: /** * @param nums: a vector of integers * @return: an integer */ int findMissing(vector<int> &nums) { // write your code here int res = 0; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); ++i) { res ^= nums[i] ^ (i + 1); } return res; } };
本文转自博客园Grandyang的博客,原文链接:寻找丢失的数字[LintCode] Find the Missing Number ,如需转载请自行联系原博主。
本文介绍了一种算法问题——寻找长度为N且包含0到N之间的整数的数组中缺失的数字。提供了两种解决方案:一种使用求和的方法找到缺失的数字,另一种采用位操作的方式解决。这些方法都在LeetCode上进行了验证。
1588

被折叠的 条评论
为什么被折叠?



