leetcode1486 官方降低时间复杂度方法

1486. 数 组异或操作 - 力扣(LeetCode)

题目:

异或运算:

相同为0,不同为1

即:

0 ^ 0 = 0 ,

0 ^ 1 = 1,

1 ^ 0 = 1 ,

1 ^ 1 = 0 ,

直接解法:

java 复制代码
class Solution {
    public int xorOperation(int n, int start) {
        int result = 0;
        for(int i = 0;i<n;i++)
        {
            int num = start + 2*i;
            result ^=num;
        }
        return result;
    }
}

降低时间复杂度

java 复制代码
class Solution {
    public int xorOperation(int n, int start) {
        int s = start >> 1, e = n & start & 1;
        int ret = sumXor(s - 1) ^ sumXor(s + n - 1);
        return ret << 1 | e;
    }

    public int sumXor(int x) {
        if (x % 4 == 0) {
            return x;
        }
        if (x % 4 == 1) {
            return 1;
        }
        if (x % 4 == 2) {
            return x + 1;
        }
        return 0;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/xor-operation-in-an-array/solutions/371258/shu-zu-yi-huo-cao-zuo-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关推荐
失散1311 小时前
分布式专题——1.1 Redis单机、主从、哨兵、集群部署
java·数据库·redis·分布式·架构
刘一说11 小时前
Linux调试命令速查:Java/微服务必备
java·linux·微服务
IT·陈寒12 小时前
怎么这么多 StringUtils —— Apache、Spring、Hutool 全面对比
java·spring·apache
AAA修煤气灶刘哥12 小时前
MySQL 查文本查哭了?来唠唠 ES 这货:从 “啥是 ES” 到 Java 撸代码,一篇整明白!
java·后端·elasticsearch
金銀銅鐵12 小时前
[Java] 浅析密封类(Sealed Classes) 在 class 文件中是如何实现的
java·后端
Hello.Reader12 小时前
一文通关 Proto3完整语法与工程实践
java·linux·数据库·proto3
DashingGuy12 小时前
算法(keep learning)
java·数据结构·算法
时间行者_知行合一12 小时前
Spring如何选择依赖注入方式
java
counting money12 小时前
JAVA泛型基础
java·开发语言·eclipse
田里的水稻12 小时前
C++_数据类型和数据结构
java·数据结构·c++