看到一位大佬的写法,感觉太有意思了,非常巧妙,学习一下。
题目描述
A non-empty array A consisting of N non-negative integers is given.
Its binarian is defined as:
binarian(A)=pow2(A[0]) + pow2(A[1]) + ... + pow2(A[N-1])
pow2(K) = 2 ^ K
For example, the binarian of array A such that:
[1, 5, 4]
equals 50:
binarian(A)=pow2(A[0]) + pow2(A[1])+ pow2(A[2]) = pow2(1)+ pow2(5)+ pow2(4) = 2 + 32 + 16 = 50
Write a function:
class Solution{public int solution(int[] A)};
that, given an array A consisting of N non-negative integers, returns the length of the shortest array that has the same binarian as array A.
For example, given array A such that [1,0,2,0,0,2]
the function should return 3 because:
• the binarian of A is 13
• array B such that B[0] = 3, B[1] = 2 and B[2] = 0 also has a binarian of 13,
• there is no shorter array with a binarian of 13.
Write an efficient algorithm for the following assumptions:
• N is an integer within the range [1..100,000]
• each element of array A is an integer within the range[0..10,000].
const int N = 10100;
class Solution{
public:
int solution(vector<int>& A)
{
bitset<N> f;
for(int i = 0; i < A.size(); i++)
{
int j = A[i];
bool flag = true;
while(flag)
{
flag = f[j] & flag;
if(flag)
f[j++] = false;
else
f[j++] = true;
}
}
return f.count();
}
};