异或1的妙处

异或1的妙处

刷lc每日一题时,看评论发现一种异或1的解法,感觉很有趣就研究了一下。

题目如下:

给你一个下标从 0 开始的整数数组 nums 。在一步操作中,你可以执行以下步骤:

从 nums 选出 两个 相等的 整数
从 nums 中移除这两个整数,形成一个 数对
请你在 nums 上多次执行此操作直到无法继续执行。

返回一个下标从 0 开始、长度为 2 的整数数组 answer 作为答案,其中 answer[0] 是形成的数对数目,answer[1] 是对 nums 尽可能执行上述操作后剩下的整数数目。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-number-of-pairs-in-array

个人题解:

public int[] numberOfPairs(int[] nums) {
    int[] res = new int[]{0,1};
    if (nums.length == 1)
        return res;
    Map<Integer, Integer> map = new HashMap<>();
    int count = 0;
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(nums[i])){
            map.remove(nums[i]);
            count++;
        }else
            map.put(nums[i], i);
    }
    int leftNumber = nums.length - count * 2;
    res[0] = count;
    res[1] = leftNumber;

    return res;
}

效率低下

评论题解:

class Solution {
    public int[] numberOfPairs(int[] nums) {
        int ans = 0;
        int[] a = new int[101];
        for (int num : nums) {
            if ((a[num] ^= 1) == 0) ans++; //判断是否重复出现过数组中数值
        }
        return new int[]{ans, nums.length - 2 * ans};
    }
}

看到异或1有点不解

经过百度和自我验证

发现如果是一个偶数异或1,那么答案是偶数+1.如果是一个奇数异或1,那么答案是奇数-1

所以上述代码中初始化的a数组中全为0,每次取到num为下标的值进行异或1,如果第一次取到则会得到1的结果,如果是第二次,则异或得到0,数对+1。

posted @ 2023-02-16 21:39  追D  阅读(45)  评论(0)    收藏  举报