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

相关推荐
咖啡Beans1 小时前
使用OpenFeign实现微服务间通信
java·spring cloud
我不是混子1 小时前
说说单例模式
java
间彧3 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧3 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧4 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng4 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663674 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧4 小时前
ThreadLocal实现原理与应用实践
java
若水不如远方5 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty