码迷,mamicode.com
首页 > 其他好文 > 详细

Missing Number - LeetCode

时间:2015-10-27 13:14:31      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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?

思路:我的方法是根据nums数组的大小,先计算出如果没有数缺少时所有数的和,利用公式 n * (n + 1) / 2即可。但这样会有溢出的危险。

看了discussion之后,被里面利用位运算的答案所深深震撼。

其主要思路就是,如果现在的数组里有一个数缺失,那么我们将这些数进行异或运算,然后再异或一遍完整的数。

那么没有缺失的数将会被异或两遍,而缺失的则只会被异或一遍。最后异或完的结果就是缺失的数字!

1 class Solution {
2 public:
3     int missingNumber(vector<int>& nums) {
4         int res = 0;
5         for (int i = 0, n = nums.size(); i < n; i++)
6             res ^= nums[i] ^ (i + 1);
7         return res;
8     }
9 };

 

Missing Number - LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/4913740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!