Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given an integer array nums
where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Constraints:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums
appears exactly three times except for one element which appears once.class Solution:
def singleNumber(self, nums):
single = 0
for i in range(32):
count = 0
for num in nums:
if num & (1<<i) == (1<<i): count += 1
single |= (count%3) << i
return single if single < (1<<31) else single - (1<<32)
int singleNumber(vector<int>& s)
{
vector<int> t(32);////Made a array contain 32 elements.
int sz = s.size();
int i, j, n;
for (i = 0; i < sz; ++i)
{
n = s[i];
for (j = 31; j >= 0; --j)
{
t[j] += n & 1;//Find the last digit.
n >>= 1;
if (!n)
break;
}
}
int res = 0;
for (j = 31; j >= 0; --j)
{
n = t[j] % 3;//"3" represents k times.
if (n)
res += 1 << (31 - j);
}
return res;
}
public int singleNumber(int[] nums) {
int ones = 0, twos = 0, threes = 0;
for (int i = 0; i < nums.length; i++) {
// twos holds the num that appears twice
twos |= ones & nums[i];
// ones holds the num that appears once
ones ^= nums[i];
// threes holds the num that appears three times
threes = ones & twos;
// if num[i] appears three times
// doing this will clear ones and twos
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
In our experience, we suggest you solve this Single Number II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Single Number II LeetCode Solution
I hope this Single Number II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>