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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关推荐
MacroZheng7 分钟前
横空出世!Claude Code画图神器来了,比Visio快10倍!
java·人工智能·后端
半夜修仙7 分钟前
延迟队列的介绍及常见问题
java·数据库·中间件·rabbitmq
2601_961963388 分钟前
React对比Vue对比Angular:构建企业级合同签署平台深度评测
java·微服务·架构
布局呆星10 分钟前
Spring Boot + AOP 操作日志实战:自定义注解、切面编程、SecurityContext 全链路贯通,一次讲透
java·spring boot·后端
lazy H10 分钟前
Maven 依赖爆红怎么办?IDEA 中 Maven 项目常见问题和解决方法总结
java·后端·学习·maven·intellij-idea
Flittly11 分钟前
【AgentScope Java新手村系列】(8)多Agent协作
java·spring boot·笔记·spring·ai
SimonKing12 分钟前
低调低调,白嫖文生图,文生视频模型,无Token限制
java·后端·程序员
我命由我1234513 分钟前
Android 开发问题:EditText 控件的 android:imeOptions=“actionDone“ 属性不生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
我登哥MVP14 分钟前
SpringCloud Alibaba 核心组件解析:服务熔断和降级
java·spring boot·后端·spring·spring cloud·java-ee·maven