Leetcode 287 寻找重复数 位计数

 

  多种解题方式,位计数感觉最精彩。

  JAVA Hash表:

    public final int findDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i])) return nums[i];
            set.add(nums[i]);
        }
        return -1;
    }

  JAVA 排序去重:

    public final int findDuplicate0(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i++) {
            int r = nums[i] ^ nums[i + 1];
            if (r == 0) return nums[i];
        }
        return -1;
    }

  JAVA 位计数:

    public final int findDuplicate(int[] nums) {
        int re = 0, len = nums.length;
        for (int i = 0; i < 32; i++) {
            int x = 0, y = 0;
            for (int j = 0; j < len; j++) {
                if (((1 << i) & nums[j]) > 0) x++;
                if (j >= 1 && (j & (1 << i)) > 0) y++;
            }
            if (x > y) re |= (1 << i);
        }
        return re;
    }

  JS 位计数:

/**
 * @param {number[]} nums
 * @return {number}
 */
var findDuplicate = function (nums) {
    let len = nums.length, re = 0;
    for (let bit = 0; bit < 32; bit++) {
        let x = 0, y = 0;
        for (let i = 0; i < len; i++) {
            if ((nums[i] & (1 << bit)) > 0) x++;
            if (i > 0 && (i & (1 << bit)) > 0) y++;
        }
        if (x > y) re |= 1 << bit;
    }
    return re;
};

 

posted @ 2021-01-22 16:39  牛有肉  阅读(66)  评论(0编辑  收藏  举报