基于链表的无序查找

2019-02-25 14:16:39 浏览数 (1)

代码语言:javascript复制
package com.snail.basic;


public class SequentialSearchST<Key, Value> {
    // 链表首结点
    private Node first;

    private class Node {
        // 链表结点定义
        Key key;
        Value val;
        Node next;

        public Node(Key key, Value val, Node next) {
            this.key = key;
            this.val = val;
            this.next = next;
        }
    }

    public Value get(Key key) {
        // 查找给定的键,返回相连的值
        for (Node x = first; x != null; x = x.next)
            if (key.equals(x.key))
                return x.val;
        return null;
    }

    public void put(Key key, Value val) {
        // 查找给定的键,找到则更新其值,否则在表中新建结点
        for (Node x = first; x != null; x = x.next)
            if (key.equals(x.key)) {
                // 命中 更新
                x.val = val;
                return;
            }
        // 未命中新建结点
        first = new Node(key, val, first);
    }

}
代码语言:javascript复制
package com.snail.basic;

/**
 * 二分查找基于有序数组
 * 
 * @param <Key> 有序排列的键
 * @param <Value> 键对应的值
 */
public class BinarySearchST<Key extends Comparable<Key>,Value> {
    private Key[] keys;
    private Value[] vals;
    private int N;
    public BinarySearchST(int capacity){
        keys = (Key[]) new Comparable[capacity];
        vals = (Value[]) new Object[capacity];
    }
    public int size(){
        return N;
    }
    public Value get(Key key){
        int i = rank(key);
        if(i<N&&keys[i].compareTo(key)==0)return vals[i];
        else return null;
        
    }
    public int rank(Key key){
        int lo = 0,hi =N-1;
        while (lo<=hi){
            int mid = lo   (hi-lo)/2;
            int cmp = key.compareTo(keys[mid]);
            if(cmp<0)hi=mid-1;
            else if(cmp>0)lo=mid 1;
            else return mid;
        }
        return lo;
    }
    public void put(Key key,Value val){
        int i = rank(key);
        if(i<N && keys[i].compareTo(key)==0){
            vals[i] = val;return;
        }
        for (int j = N; j > i; j--) {
            keys[j]= keys[j-1];
            vals[j] = vals[j-1];
        }
        keys[i]=key;
        vals[i]=val;
        N  ;
    }
}

0 人点赞