LeetCode 75| 位运算

目录

[338 比特位计数](#338 比特位计数)

[136 只出现一次的数字](#136 只出现一次的数字)

[1318 或运算的最小翻转次数](#1318 或运算的最小翻转次数)


338 比特位计数

cpp 复制代码
class Solution {
public:
    vector<int> countBits(int n) {
        vector<int>res(n + 1);
        for(int i = 0;i <= n;i++)res[i] = cal(i);
        return res;
    }
    int cal(int num){
        int res = 0;
        for(int i = 0;i < 32;i++)res += (num >> i) & 1;
        return res;
    }
};

时间复杂度O(n)

空间复杂度O(n)

136 只出现一次的数字

cpp 复制代码
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        for(auto num : nums){
            res ^= num;
        }
        return res;
    }
};

时间复杂度O(n)

空间复杂度O(1)

1318 或运算的最小翻转次数

cpp 复制代码
class Solution {
public:
    int minFlips(int a, int b, int c) {
        int res = 0;
        while(a || b || c){
            if(c & 1){
                if((a & 1) == 0 && (b & 1) == 0)res++;
            }else{
                if(a & 1)res++;
                if(b & 1)res++;
            }
            a>>=1;
            b>>=1;
            c>>=1;
        }
        return res;
    }
};

时间复杂度O(n)//n为a,b,c 的最大二进制位数

空间复杂度O(1)

相关推荐
半桔1 小时前
【STL源码剖析】二叉世界的平衡:从BST 到 AVL-tree 和 RB-tree 的插入逻辑
java·数据结构·c++·算法·set·map
塔中妖2 小时前
【华为OD】分割数组的最大差值
数据结构·算法·华为od
weixin_307779132 小时前
最小曲面问题的欧拉-拉格朗日方程 / 曲面极值问题的变分法推导
算法
RTC老炮2 小时前
webrtc弱网-AlrDetector类源码分析与算法原理
服务器·网络·算法·php·webrtc
孤廖2 小时前
【算法磨剑:用 C++ 思考的艺术・Dijkstra 实战】弱化版 vs 标准版模板,洛谷 P3371/P4779 双题精讲
java·开发语言·c++·程序人生·算法·贪心算法·启发式算法
sali-tec2 小时前
C# 基于halcon的视觉工作流-章33-矩状测量
开发语言·人工智能·算法·计算机视觉·c#
songx_993 小时前
leetcode29( 有效的括号)
java·数据结构·算法·leetcode
于樱花森上飞舞3 小时前
【java】常见排序算法详解
java·算法·排序算法
GawynKing3 小时前
图论3 图的遍历
算法·深度优先
东方芷兰5 小时前
Leetcode 刷题记录 21 —— 技巧
java·算法·leetcode·职场和发展·github·idea