Java 为01序列实现快速 HashSet

01 数组

import java.util.BitSet;
import java.util.HashMap;
import java.util.Arrays;

public class FastHashSet {
    private HashMap<Integer, BitSet> map = new HashMap<>();

    public void add(int[] array) {
        BitSet bitSet = new BitSet(array.length);
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 1) {
                bitSet.set(i);
            }
        }
        map.put(Arrays.hashCode(array), bitSet);
    }

    public boolean contains(int[] array) {
        BitSet bitSet = new BitSet(array.length);
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 1) {
                bitSet.set(i);
            }
        }
        BitSet existingBitSet = map.get(Arrays.hashCode(array));
        return existingBitSet != null && existingBitSet.equals(bitSet);
    }
}

01 矩阵

import java.util.Arrays;

public class Matrix {
    private int[][] data;

    public Matrix(int[][] data) {
        this.data = data;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Matrix matrix = (Matrix) o;
        return Arrays.deepEquals(data, matrix.data);
    }

    @Override
    public int hashCode() {
        return Arrays.deepHashCode(data);
    }
}
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<Matrix> set = new HashSet<>();
        // 添加新的二维数组
        set.add(new Matrix(new int[][]{{1, 0}, {0, 1}}));
        // 检查二维数组是否存在
        System.out.println(set.contains(new Matrix(new int[][]{{1, 0}, {0, 1}})));
    }
}

你可能感兴趣的:(java,python,开发语言)