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? 方法一: 与single number思想相似 按位操作(使用XOR ^)
class Solution {public: int missingNumber(vector<int>& nums) { int len = nums.size(); int e = 0; for(int i = 0; i < len; i++){ e ^= (i + 1) ^ nums[i]; } return e; }};方法二: 先排序后寻找;
class Solution {public: int missingNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); if(nums[0] == 1) return 0; int i = 0; for(; i < nums.size()-1; i++){ if(nums[i+1] - nums[i] != 1) return nums[i] + 1; } return nums[nums.size()-1] + 1; }};新闻热点
疑难解答