[leetcode] 【数组】 137. Single Number II
2016-05-30 10:32
260 查看
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
把nums数组所有数都按位加在count数组中,然后对3求余,剩下的数就是只出现一次的数。
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题意
一个整数数组中,有一个元素只出现一次,其他每个元素都出现3次,找出这个元素。题解
这里也是根据位的特性来处理,用于一个int所占bit数大小的数组count来存储二进制数的每一位。把nums数组所有数都按位加在count数组中,然后对3求余,剩下的数就是只出现一次的数。
class Solution { public: int singleNumber(vector<int>& nums) { const int sizeint=sizeof(int)*8; vector<int> count(sizeint); for(auto i: nums) { for(int j=0;j<sizeint;j++) { count[j]+=(i>>j) &1; count[j]%=3; } } int res=0; for(int i=0;i<sizeint;i++) res+=(count[i]<<i); return res; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解