数据结构-映射Map

一 什么是映射?

借助关键码直接查找数据元素并对其进行操作的数据结构就是映射,映射中的数据是以(key, value)的形式进行存储的,其中 key 为关键码对象,value 为具体的数据对象。生活中有很多地方都使用这样的数据结构来存储数据,比如:字典 车牌号 身份证等
映射图示

二 基于链表的映射实现

1⃣️ 定义Map接口
package com.mufeng.map;

/**
 * Created by wb-yxk397023 on 2018/7/5.
 */
public interface Map {

    /**
     * 向Map中添加元素
     * @param key
     * @param value
     */
    void add(K key, V value);

    /**
     * 根据K值找到V,并从Map中删除
     * @param key
     * @return
     */
    V remove(K key);

    /**
     * 根据K值查看Map中是否包含该元素
     * @param key
     * @return
     */
    boolean contains(K key);

    /**
     * 根据K值查询V值
     * @param key
     * @return
     */
    V get(K key);

    /**
     * 根据K值修改Value值
     * @param key
     * @param newValue
     */
    void set(K key, V newValue);

    /**
     * 查看Map中的元素个数
     * @return
     */
    int getSize();

    /**
     * 查看Map是否为空
     * @return
     */
    boolean isEmpty();
}
2⃣️ 实现具体的Map类
package com.mufeng.map;


/**
 * Created by wb-yxk397023 on 2018/7/5.
 */
public class LinkedListMap implements Map {

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);

        if (node == null){
            dummyHead.next = new Node(key, value, dummyHead.next);
            size++;
        }else {
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {

        Node prev = dummyHead;

        while (prev.next != null){
            if (prev.next.key.equals(key)){
                break;
            }
            prev = prev.next;
        }

        if (prev.next != null){
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size--;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.value;
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(key);

        if (node == null){
            throw new IllegalArgumentException(key + " doesn't exist!");
        }

        node.value = newValue;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    private Node dummyHead;
    private int size;

    public LinkedListMap(){
        dummyHead = new Node();
        size = 0;
    }

    /**
     * 通用方法封装
     * @param key
     * @return
     */
    private Node getNode(K key){
        Node cur = dummyHead.next;

        while (cur != null){
            if (cur.key.equals(key)){
                return cur;
            }
            cur = cur.next;
        }

        return null;
    }

    /**
     * 内部类Node
     */
    private class Node{
        private K key;
        private V value;
        private Node next;

        public Node(K key, V value, Node next){
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key){
            this(key,null,null);
        }

        public Node(){
            this(null,null,null);
        }

        @Override
        public String toString(){
            return key.toString() + " : " + value.toString();
        }
    }
}
3⃣️ 测试
public static void main(String[] args){

        System.out.println("Pride and Prejudice");

        ArrayList words = new ArrayList<>();
        if(FileOperation.readFile("pride-and-prejudice.txt", words)) {
            System.out.println("Total words: " + words.size());

            LinkedListMap map = new LinkedListMap<>();
            for (String word : words) {
                if (map.contains(word))
                    map.set(word, map.get(word) + 1);
                else
                    map.add(word, 1);
            }

            System.out.println("Total different words: " + map.getSize());
            System.out.println("Frequency of PRIDE: " + map.get("pride"));
            System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
        }

        System.out.println();
    }

本次测试实例中使用的工具类与Set中使用的是一致的;
测试结果

三 基于二分搜索树的映射实现

1⃣️ 实现具体的Map类
package com.mufeng.map;

/**
 * Created by wb-yxk397023 on 2018/7/5.
 */
public class BSTMap, V> implements Map{


    @Override
    public void add(K key, V value) {
        root = add(root, key, value);
    }

    @Override
    public V remove(K key) {
        Node node = getNode(root, key);

        if (node != null){
            root = remove(root, key);
            return node.value;
        }

        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(root, key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(root, key);
        return node == null ? null : node.value;
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(root, key);

        if (node == null){
            throw new IllegalArgumentException(key + " doesn't exist! ");
        }
        node.value = newValue;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    private Node root;
    private int size;

    public BSTMap(){
        root = null;
        size = 0;
    }

    // 返回以node为根的二分搜索树的最小值所在的节点
    private Node minimum(Node node){
        if(node.left == null)
            return node;
        return minimum(node.left);
    }

    // 删除掉以node为根的二分搜索树中的最小节点
    // 返回删除节点后新的二分搜索树的根
    private Node removeMin(Node node){

        if(node.left == null){
            Node rightNode = node.right;
            node.right = null;
            size --;
            return rightNode;
        }

        node.left = removeMin(node.left);
        return node;
    }

    /**
     * 删除掉以node为根的二分搜索树中值为key的节点, 递归算法
     * 返回删除节点后新的二分搜索树的根
     * @param node
     * @param key
     * @return
     */
    private Node remove(Node node, K key){

        if( node == null )
            return null;

        if( key.compareTo(node.key) < 0 ){
            node.left = remove(node.left , key);
            return node;
        }
        else if(key.compareTo(node.key) > 0 ){
            node.right = remove(node.right, key);
            return node;
        }
        else{   // key.compareTo(node.key) == 0

            // 待删除节点左子树为空的情况
            if(node.left == null){
                Node rightNode = node.right;
                node.right = null;
                size --;
                return rightNode;
            }

            // 待删除节点右子树为空的情况
            if(node.right == null){
                Node leftNode = node.left;
                node.left = null;
                size --;
                return leftNode;
            }

            // 待删除节点左右子树均不为空的情况

            // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
            // 用这个节点顶替待删除节点的位置
            Node successor = minimum(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;

            node.left = node.right = null;

            return successor;
        }
    }
    /**
     * 返回以node为根节点的二分搜索树中,key所在的节点
     * @param node
     * @param key
     * @return
     */
    private Node getNode(Node node, K key){
        if (node == null){
            return null;
        }

        if (key.compareTo(node.key) == 0){
            return node;
        }else if (key.compareTo(node.key) < 0){
            return getNode(node.left, key);
        }else {
            return getNode(node.right, key);
        }
    }

    /**
     * 向以node为根的二分搜索树中插入元素,递归算法
     * 返回插入新节点后二分搜索树的根
     * @param node
     * @param key
     * @param value
     * @return
     */
    private Node add(Node node, K key, V value){
        // 递归的终止条件
        if (node == null){
            size++;
            return new Node(key, value);
        }

        // 递归调用
        if (key.compareTo(node.key) < 0){
            node.left = add(node.left, key, value);
        }else if (key.compareTo(node.key) > 0){
            node.right = add(node.right, key, value);
        }else if (key.compareTo(node.key) == 0){
            node.value = value;
        }

        return node;
    }

    /**
     * 内部类
     */
    private class Node{
        public K key;
        public V value;
        public Node left, right;

        public Node(K key, V value){
            this.key = key;
            this.value = value;
            left = null;
            right = null;
        }
    }
}
2⃣️ 测试
public static void main(String[] args){

        System.out.println("Pride and Prejudice");

        ArrayList words = new ArrayList<>();
        if(FileOperation.readFile("pride-and-prejudice.txt", words)) {
            System.out.println("Total words: " + words.size());

            BSTMap map = new BSTMap<>();
            for (String word : words) {
                if (map.contains(word))
                    map.set(word, map.get(word) + 1);
                else
                    map.add(word, 1);
            }

            System.out.println("Total different words: " + map.getSize());
            System.out.println("Frequency of PRIDE: " + map.get("pride"));
            System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
        }

        System.out.println();
    }
测试结果

四 两种实现方式的性能对比

1⃣️ 测试类
import java.util.ArrayList;

public class Main {

    private static double testMap(Map map, String filename){

        long startTime = System.nanoTime();

        System.out.println(filename);
        ArrayList words = new ArrayList<>();
        if(FileOperation.readFile(filename, words)) {
            System.out.println("Total words: " + words.size());

            for (String word : words){
                if(map.contains(word))
                    map.set(word, map.get(word) + 1);
                else
                    map.add(word, 1);
            }

            System.out.println("Total different words: " + map.getSize());
            System.out.println("Frequency of PRIDE: " + map.get("pride"));
            System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
        }

        long endTime = System.nanoTime();

        return (endTime - startTime) / 1000000000.0;
    }

    public static void main(String[] args) {

        String filename = "pride-and-prejudice.txt";

        BSTMap bstMap = new BSTMap<>();
        double time1 = testMap(bstMap, filename);
        System.out.println("BST Map: " + time1 + " s");

        System.out.println();

        LinkedListMap linkedListMap = new LinkedListMap<>();
        double time2 = testMap(linkedListMap, filename);
        System.out.println("Linked List Map: " + time2 + " s");

    }
}
测试结果

你可能感兴趣的:(数据结构-映射Map)