首页 > 学院 > 开发设计 > 正文

LEETCODE--Missing Number

2019-11-11 05:55:48
字体:
来源:转载
供稿:网友

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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表