[LeetCode] Missing Number
来源:互联网 发布:相思相见知何日 编辑:程序博客网 时间:2024/05/01 04:12
Missing Number
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
解题思路:
题意为找出0~n中缺少的那个数。要求O(n)的时间复杂度和O(1)的空间复杂度。
若采用排序查找的办法,则需要O(nlogn)的时间。
若采用hash的办法,则需要O(n)的空间复杂度。
采用位操作的办法。对数组中数的二进制位的1进行计数。然后对0~n中的二进制位的1进行计数。则两次计数的差则是missing number贡献的。
class Solution {public: int missingNumber(vector<int>& nums) { vector<int> bitCount(sizeof(int) * 8, 0); //n + 1个数中的bit计数 vector<int> missingBitCount(sizeof(int) * 8, 0); //n个数中的bit计数 int len = nums.size(); for(int i=0; i<len; i++){ int j = 0; int num = nums[i]; while(num){ if(num & 1){ missingBitCount[j]++; } j++; num = num >> 1; } } for(int i = 0; i<=len; i++){ int j = 0; int num = i; while(num){ if(num & 1){ bitCount[j]++; } j++; num = num >> 1; } } int result = 0; for(int i = sizeof(int) * 8 - 1; i>=0; i--){ result = result << 1; result += bitCount[i] - missingBitCount[i]; } return result; }};
0 0
- 【LeetCode】268 Missing Number
- [leetcode] 268.Missing Number
- [leetcode][math] Missing Number
- [LeetCode] Missing Number
- Leetcode -- Missing Number
- 【leetCode】Missing Number
- [Leetcode]Missing Number
- leetcode Missing Number
- 【leetcode】268. Missing Number
- [leetcode] Missing Number
- LeetCode(268)Missing Number
- Leetcode: Missing Number
- LeetCode之Missing Number
- LeetCode Missing Number
- [leetcode 268]Missing Number
- leetcode--Missing Number
- leetCode #286 Missing Number
- Leetcode 286 : Missing Number
- UVA11990 ``Dynamic'' Inversion (树状数组套平衡树)
- 论文笔记 《What makes for effective detection proposals?》
- C#堆内存分配和栈内存分配
- Java____进程、线程学习、处理器调度(转)
- [LeedCode OJ]#171 Excel Sheet Column Number
- [LeetCode] Missing Number
- Linux 文件操作
- const指针、void指针
- POJ3258--------River Hopscotch
- iOS第三方开源库的吐槽和备忘
- android开发问题 Failed to pull selection
- JAVA代码url请求
- Java 持久化技术规范(JPA)中的主键生成策略
- 几种菜单