LeetCode刷题(44)~缺失数字【位运算:异或 】
【摘要】 题目描述
给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
12
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
12
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
解答 By 海轰
提交代码
...
题目描述
给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
- 1
- 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
- 1
- 2
说明:
- 你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
解答 By 海轰
提交代码
int missingNumber(vector<int>& nums) { int len=nums.size(); int sum=((len+1)*len)/2; for(int i=0;i<len;++i) sum-=nums[i]; return sum; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
运行结果
思路
首先计算出0-n的算术和,然后依次减去数组中的每一项,剩下的数就是缺失的数。
解答
位运算
int missingNumber(vector<int>& nums) { int result=nums.size(); for(int i=0;i<nums.size();++i) result^=i^nums[i]; return result; }
- 1
- 2
- 3
- 4
- 5
- 6
运算结果
算法思路😆:相同数字异或为0
题目来源
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnj4mt/
来源:力扣(LeetCode)
参考:https://leetcode-cn.com/problems/missing-number/solution/que-shi-shu-zi-by-leetcode/
文章来源: haihong.blog.csdn.net,作者:海轰Pro,版权归原作者所有,如需转载,请联系作者。
原文链接:haihong.blog.csdn.net/article/details/108009588
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)