[按位与的通用模板]leetcode1521:找到最接近目标值的函数值(hard)

该博客介绍了一种使用位运算解决子数组按位与运算的问题,通过遍历数组,不断更新与运算结果,并存储在一个集合中。最终找到与目标值t最接近的与运算结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
在这里插入图片描述
在这里插入图片描述


题解:

思路:位运算


代码如下:

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值