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

相关推荐
能工智人小辰6 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT6 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄8 分钟前
设计模式之外观模式
java·设计模式·外观模式
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep1 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai1 小时前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
Codebee1 小时前
OneCode:AI时代的先锋——注解驱动技术引领开发范式变革
java
勤奋的知更鸟1 小时前
Java 编程之状态模式
java·开发语言·状态模式