题目:
题解:
思路:位运算
- 将 898. 子数组按位或操作 的 或运算 改为 与运算,然后在 v 中寻找距离 t 最近的与运算结果值即可。
代码如下:
class Solution {
public:
int closestToTarget(vector<int>& a, int t) {
// ors 保留前面子数组的与运算的所有结果值
unordered_set<int> v,ors;
for(int x:a)
{
unordered_set<int> tmp;
// 将 ors 中的各元素与当前元素进行与运算
for(auto it=ors.begin();it!=ors.end();it++)
tmp.insert(*it&x);
// 插入当前元素
tmp.insert(x);
ors=tmp;
// 与原来保存所有与运算结果值的 v 做并集
for(auto it=tmp.begin();it!=tmp.end();it++)
v.insert(*it);
}
int res=INT_MAX;
for(auto it=v.begin();it!=v.end();it++){
res=min(res,abs(*it-t));
}
return res;
}
};