当前位置:网站首页>LeetCode 898. 子数组按位或操作 - set
LeetCode 898. 子数组按位或操作 - set
2022-04-22 05:36:00 【Guapifang】
- 子数组按位或操作
我们有一个非负整数数组 arr 。
对于每个(连续的)子数组 sub = [arr[i], arr[i + 1], …, arr[j]] ( i <= j),我们对 sub 中的每个元素进行按位或操作,获得结果 arr[i] | arr[i + 1] | … | arr[j] 。
返回可能结果的数量。 多次出现的结果在最终答案中仅计算一次。
示例 1:
输入:arr = [0]
输出:1
解释:
只有一个可能的结果 0 。
示例 2:
输入:arr = [1,1,2]
输出:3
解释:
可能的子数组为 [1],[1],[2],[1, 1],[1, 2],[1, 1, 2]。
产生的结果为 1,1,2,1,3,3 。
有三个唯一值,所以答案是 3 。
示例 3:
输入:arr = [1,2,4]
输出:6
解释:
可能的结果是 1,2,3,4,6,以及 7 。
提示:
1 <= nums.length <= 5 * 104
0 <= nums[i] <= 109
题解
不断用set去重,一开始先写了个暴力版的,想着可能会超时,没想到过了,瑟瑟发抖。
AC代码
class Solution {
public:
set<int>q,q2,q3;
int subarrayBitwiseORs(vector<int>& arr)
{
q.insert(arr[0]);
q3.insert(arr[0]);
for(int i=1;i<arr.size();i++)
{
q2 = q3;
q3.clear();
set<int>::iterator it = q2.begin();
while(it!=q2.end())
{
q3.insert(*it|arr[i]);
q.insert(*it|arr[i]);
it++;
}
q3.insert(arr[i]);
//储存自己本身
q.insert(arr[i]);
}
int ans = 0;
set<int>::iterator it = q.begin();
while(it!=q.end())
{
ans ++;
it++;
}
return ans;
}
};

版权声明
本文为[Guapifang]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43918046/article/details/123641580
边栏推荐
猜你喜欢
随机推荐
环形链表2
opencv 骨架提取/图片细化 代码
vscode cmake-tools launching.json 使用文档(垃圾翻译)
5.The Simple Problem
raspberry keras-ocr can‘t allocate memory in static TLS block
代码整洁之道学习
JVM探究
元注解(注解的注解)
AcWing 1096. 地牢大师(三维 BFS)代码详细注释
数据挖掘——序列模式挖掘
mysql建表最佳实践
Installing mysql8 under Linux
Do you know the implementation of strcpy?
Advanced part of MySQL
codeforces div2 777 A
关于form表单点击submit按钮后,页面自动刷新的问题解决
多线程Executors的使用
最长上升子序列(lis)
SQL优化最佳实践
我常用的开发软件









