题目:
解答:
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) 4 { 5 int i = 0; 6 int j = nums.size() - 1; 7 8 while(i <= j) 9 { 10 int m = (i + j) / 2; 11 12 if(nums[m] == m) 13 { 14 i = m + 1; 15 } 16 else 17 { 18 j = m - 1; 19 } 20 } 21 return i; 22 } 23 };
方法二:位运算
根据位运算的知识我们知道0与任何数的异或还是其本身,任何数与其自身异或结果为0。
对于长度为n的序列中丢失了一个数,索引就会缺少n本身,所以我们选择n和列表中的元素以及索引求异或。
因为丢失的数是只有一个,其他的数都是成对出现,成对出现的数异或值为0,所以最后剩的就是丢失的数。
时间复杂度O(n),空间复杂度O(1)。
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) 4 { 5 int n = nums.size(); 6 int res = 0; 7 for(int i = 0;i < n;i++) 8 { 9 res ^= (nums[i] ^ i); 10 } 11 12 return res ^ n; 13 } 14 };
原文:https://www.cnblogs.com/ocpc/p/12830671.html