LeetCode 算法 每日一题 1486.数组异或操作

1486.数组异或操作

题目描述

给你两个整数,nstart
数组nums定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length
请返回nums中所有元素按位异或(XOR)后得到的结果。

示例1

输入:n = 5, start = 0
输出:8
解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
“^” 为按位异或 XOR 运算符。

示例2

输入:n = 4, start = 3
输出:8
解释:数组 nums 为 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.

示例3

输入:n = 1, start = 7
输出:7

示例4

输入:n = 10, start = 5
输出:2

提示

    1 <= n <= 1000
    0 <= start <= 1000
    n == nums.length
    模拟这个过程,创建一个数组nums并返回它的所有元素的按位异或。

代码演示
Java 模拟数组

import java.util.stream.IntStream;

public class OneQuestionPerDay1486 {
    public static void main(String[] args) {

        Solution s = new Solution();
        System.out.println(s.xorOperation(5,0));
        System.out.println(s.xorOperation(4,3));

        Solution1486_02 s2 = new Solution1486_02();
        System.out.println(s2.xorOperation(1,7));
        System.out.println(s2.xorOperation(10,5));

    }
}

class Solution {
    public int xorOperation(int n, int start) {
        int xor = start;
        for (int i = 1; i < n; i++) {
            int x = start + 2 * i;
            xor = xor ^ x;
        }
        return xor;
    }
}

class Solution1486_02 {
    public int xorOperation(int n, int start) {
        // IntStream 是一个原始整数值序列 lambda表达式map链式编程
        return IntStream.range(0, n).boxed().map(i -> (2 * i + start)).reduce(0, (o1, o2) -> o1 ^= o2);
    }
}

Java Solution 提交结果
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:34.9 MB, 在所有 Java 提交中击败了97.92% 的用户

Java Solution_2 提交结果
执行用时:4 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:35.4 MB, 在所有 Java 提交中击败了10.57% 的用户

代码演示
C++ 数学方法总结公式

#include <bits/stdc++.h>
using namespace std;

/* 数学方法
sumXOR{
  x           x = 4 * k
  1           x = 4 * k + 1
  x + 1       x = 4 * k + 2
  0           x = 4 * k + 3
}
result = (sumXOR(S - 1) ⊕ (sumXOR(S + n - 1)) * 2 + E)
*/
class Solution {
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;
    }

    int xorOperation(int n, int start) {
        int S = start >> 1;
        int E = n & start & 1;
        int result = sumXor(S - 1) ^ sumXor(S + n - 1);
        return result << 1 | E;
    }
};

int main()
{
  Solution s;

  cout << s.xorOperation(5,0) << endl;
  cout << s.xorOperation(4,3) << endl;
  cout << s.xorOperation(1,7) << endl;
  cout << s.xorOperation(10,5) << endl;

  return 0;
}

C++ 提交结果
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:5.7 MB, 在所有 C++ 提交中击败了96.03% 的用户

相比于模拟方法,数学方法更有算法的感觉,简单题并不简单

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W.Lionel.Esaka

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值