Algorithm <primary> - Chapter queue, stack, hash table related issues

Algorithm <primary> - Chapter second data structure

Title queue and stack with a fixed-size array implemented (title side)

Array achieve a fixed size stack

/***
*   size是对头索引(initSize是固定大小) 也是当前栈大小
*   size=下个进队index
*   size-1=下个出队index
*   size==initSize时队满 判满
*   size==0时队空 判空
***/

public static class ArrayStack {
    private Integer[] arr;
    private Integer size;   /

    public ArrayStack(int initSize) {
        if (initSize < 0) {
            throw new IllegalArgumentException("The init size is less than 0");
        }
        arr = new Integer[initSize];
        size = 0;
    }

    public Integer peek() {     //返回栈头元素
        if (size == 0) {
            return null;
        }
        return arr[size - 1];
    }

    public void push(int obj) {
        if (size == arr.length) {
            throw new ArrayIndexOutOfBoundsException("The queue is full");
        }
        arr[size++] = obj;
    }

    public Integer pop() {
        if (size == 0) {
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        return arr[--size];
    }
}

To achieve a fixed size queue array

/***
*   size当前队列大小;用size关联first/last更加方便
*   last队尾
*   first队头
*   循环队列:
*   first = first == arr.length - 1 ? 0 : first + 1;
*   last = last == arr.length - 1 ? 0 : last + 1; 
***/
public static class ArrayQueue {
    private Integer[] arr;
    private Integer size;
    private Integer first;
    private Integer last;

    public ArrayQueue(int initSize) {
        if (initSize < 0) {
            throw new IllegalArgumentException("The init size is less than 0");
        }
        arr = new Integer[initSize];
        size = 0;
        first = 0;
        last = 0;
    }

    public Integer peek() { //查看队头元素
        if (size == 0) {
            return null;
        }
        return arr[first];
    }

    public void push(int obj) {    //进队
        if (size == arr.length) {
            throw new ArrayIndexOutOfBoundsException("The queue is full");
        }
        size++;
        arr[last] = obj;
        last = last == arr.length - 1 ? 0 : last + 1; //循环队列
    }

    public Integer poll() {      //出队弹出
        if (size == 0) {
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        size--;
        int tmp = first;
        first = first == arr.length - 1 ? 0 : first + 1;
        return arr[tmp];
    }
}

Topic two: to achieve a specific stack

  • The expression Title: implement a special stack, the stack in the basic functions implemented again return stack to achieve minimum operation.
    [] Requirements:
    1. POP, Push, geiMin operation time complexity O (. 1)
    2. Stack design may use ready-made type stack structure

  • thought:
    • The basic structure of the stack - doubly linked list / dynamic array
    • An idea: to construct two stacks, a data stack, a stack min. Drawing data stack push element, while the minimum min stack push elements (each element to compare with a top element, who is who small pressure). Stack the two stacks simultaneously pop
      • data:||32415
      • I: || 32211
    • Two ideas: two stack configuration, data / min stack. data stack is pushed onto the stack element, the top element min comparison, the smaller min while pressed into the stack, or not pushed onto the stack. When the stack of the comparison, data elements stack pop the top element = min, min stack is popped.
      • data:||32415
      • I: 321 ||

A thought

  • Algorithm (Java)
public static class MyStack1 {           //思路一
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack1() {
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }

        public void push(int newNum) {
            if (this.stackMin.isEmpty()) {
                this.stackMin.push(newNum);
            } else if (newNum <= this.getmin()) {
                this.stackMin.push(newNum);
            }
            this.stackData.push(newNum);
        }

        public int pop() {
            if (this.stackData.isEmpty()) {
                throw new RuntimeException("Your stack is empty.");
            }
            int value = this.stackData.pop();
            if (value == this.getmin()) {
                this.stackMin.pop();
            }
            return value;
        }

        public int getmin() {
            if (this.stackMin.isEmpty()) {
                throw new RuntimeException("Your stack is empty.");
            }
            return this.stackMin.peek();
        }
    }

Ideas two

  • Algorithm (Java)
public static class MyStack2 {          //思路二
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack2() {
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }

        public void push(int newNum) {
            if (this.stackMin.isEmpty()) {
                this.stackMin.push(newNum);
            } else if (newNum < this.getmin()) {
                this.stackMin.push(newNum);
            } else {
                int newMin = this.stackMin.peek();
                this.stackMin.push(newMin);
            }
            this.stackData.push(newNum);
        }

        public int pop() {
            if (this.stackData.isEmpty()) {
                throw new RuntimeException("Your stack is empty.");
            }
            this.stackMin.pop();
            return this.stackData.pop();
        }

        public int getmin() {
            if (this.stackMin.isEmpty()) {
                throw new RuntimeException("Your stack is empty.");
            }
            return this.stackMin.peek();
        }
    }

Topic three: queue implementation Stack / Stack queue (flexible application)

Stack queue implementation

  • Thinking
    • Stack two queues implemented
    • First the whole sequence into a first queue, the following:
      • Finally, a number of other elements to retain all of the queue to enter the second queue
      • The first value of the output queue (ie, let the last coming in first out)
      • After the second queue into the first queue in the same manner, the output of the last element
  • Show
    • Air 54321 -> 54321 Output 5
    • Empty 4321--> 3214 Output 4

+ Algorithm (Java)

public static class TwoQueuesStack {
        private Queue<Integer> queue;
        private Queue<Integer> help;

        public TwoQueuesStack() {
            queue = new LinkedList<Integer>();
            help = new LinkedList<Integer>();
        }

        public void push(int pushInt) {
            queue.add(pushInt);
        }

        public int peek() {     //得到栈顶元素
            if (queue.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while (queue.size() != 1) {
                help.add(queue.poll());
            }
            int res = queue.poll();     //res为最后一个入队元素
            help.add(res);
            swap();     //两个栈引用交换一下
            return res;
        }

        public int pop() {
            if (queue.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while (queue.size() != 1) {
                help.add(queue.poll());
            }
            int res = queue.poll();
            swap();
            return res;
        }

        private void swap() {
            Queue<Integer> tmp = help;
            help = queue;
            queue = tmp;
        }

    }

Stack queue

  • Thinking
    • Queue with two stacks: stack designed to do a first push, the second stack pop specializing
    • Directly into the first stack, all into a second stack, the second stack, then all of the stack, to achieve FIFO
    • A stack top second stack opportunity:
      1. When the pop stack Central African space-time, push the stack fail
      2. pop stack push down is empty, the idea must complete a one-time down
    • As long as these two conditions are met, no matter at what time the countdown operation takes place, are certain to
  • Algorithm (Java)
public static class TwoStacksQueue {
        private Stack<Integer> stackPush;
        private Stack<Integer> stackPop;

        public TwoStacksQueue() {
            stackPush = new Stack<Integer>();
            stackPop = new Stack<Integer>();
        }

        public void push(int pushInt) {
            stackPush.push(pushInt);
        }

        public int poll() {
            if (stackPop.empty() && stackPush.empty()) {
                throw new RuntimeException("Queue is empty!");
            } else if (stackPop.empty()) {          //倒数操作 
                while (!stackPush.empty()) {
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.pop();
        }

        public int peek() {
            if (stackPop.empty() && stackPush.empty()) {
                throw new RuntimeException("Queue is empty!");
            } else if (stackPop.empty()) {
                while (!stackPush.empty()) {
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.peek();
        }
    }

Topic Four: dogs and cats queue

  • Topic expressions: the following cats dogs, cats and dogs achieve a queue structure
    • Methods add cat / dog class instance enqueued
    • pollAll method to all instances of a team
    • pollDog method all instances the dog team
    • The same method pollCat
    • isEmpty example method of determining whether there CATS
    • The same method isDogEmpty
    • The same method isCatEmpty
  • Dogs and Cats Type:
public static class Pet {
        private String type;

        public Pet(String type) {
            this.type = type;
        }

        public String getPetType() {
            return this.type;
        }
    }

    public static class Dog extends Pet {
        public Dog() {
            super("dog");
        }
    }

    public static class Cat extends Pet {
        public Cat() {
            super("cat");
        }
    }
  • Thinking
    • Cats and dogs each queue, queue indicated package type PetEnterQueue, pet class encapsulates a count and a flag.
    • all series function is based on the size of the count flag to decide who should head the same team
  • Algorithm (Java)
public static class PetEnterQueue {     //为了不修改底层类,封装进一个新类
        private Pet pet;    
        private long count;     //标记自己是几号,衡量猫狗谁先出

        public PetEnterQueue(Pet pet, long count) {
            this.pet = pet;
            this.count = count;
        }

        public Pet getPet() {
            return this.pet;
        }

        public long getCount() {
            return this.count;
        }

        public String getEnterPetType() {
            return this.pet.getPetType();
        }
    }

    public static class DogCatQueue {
        private Queue<PetEnterQueue> dogQ;
        private Queue<PetEnterQueue> catQ;
        private long count;

        public DogCatQueue() {
            this.dogQ = new LinkedList<PetEnterQueue>();
            this.catQ = new LinkedList<PetEnterQueue>();
            this.count = 0;
        }

        public void add(Pet pet) {
            if (pet.getPetType().equals("dog")) {
                this.dogQ.add(new PetEnterQueue(pet, this.count++));
            } else if (pet.getPetType().equals("cat")) {
                this.catQ.add(new PetEnterQueue(pet, this.count++));
            } else {
                throw new RuntimeException("err, not dog or cat");
            }
        }

        public Pet pollAll() {
            if (!this.dogQ.isEmpty() && !this.catQ.isEmpty()) {
                if (this.dogQ.peek().getCount() < this.catQ.peek().getCount()) {
                    return this.dogQ.poll().getPet();
                } else {
                    return this.catQ.poll().getPet();
                }
            } else if (!this.dogQ.isEmpty()) {
                return this.dogQ.poll().getPet();
            } else if (!this.catQ.isEmpty()) {
                return this.catQ.poll().getPet();
            } else {
                throw new RuntimeException("err, queue is empty!");
            }
        }

        public Dog pollDog() {
            if (!this.isDogQueueEmpty()) {
                return (Dog) this.dogQ.poll().getPet();
            } else {
                throw new RuntimeException("Dog queue is empty!");
            }
        }

        public Cat pollCat() {
            if (!this.isCatQueueEmpty()) {
                return (Cat) this.catQ.poll().getPet();
            } else
                throw new RuntimeException("Cat queue is empty!");
        }

        public boolean isEmpty() {
            return this.dogQ.isEmpty() && this.catQ.isEmpty();
        }

        public boolean isDogQueueEmpty() {
            return this.dogQ.isEmpty();
        }

        public boolean isCatQueueEmpty() {
            return this.catQ.isEmpty();
        }

    }

Hash table

  • CRUD default time complexity of O (1), but the relatively large constant term - because when the hash function value calculated in the cost of a relatively large

Hash function hashmap

  • nature
    1. Unlimited input fields, output fields Finite
    2. A hash function is not random function, the same input must obtain the same output same input same out
    3. Hash collision : different inputs can also get the same output diff input same out
    4. Discrete hash function : Although the nature of ①, but different input obtained on the output field will be a uniform distribution of the return value (the most important property) -> input to disrupt regularity

Hash table / hash

  • The Classical structures: a group composed of an array of output fields, each value corresponding to a set of input values ​​list. Input value to obtain a corresponding output value of a hash function field, and then mount the chain array values.
  • Hash table expansion
    • When loading the list is too long, a hash table may be selected expansion, expansion multiplied, can be done time complexity O (1)
    • Offline expansion, expansion frequency is not frequent
  • Java hash table implementation structure: the output field is still an array of arrays, each value after the mount is a red-black tree treemap
  • hashset & hashmap
    • Actually hash table, the former add (key), the latter put (key, value), value is actually the key out of a multi-accompanying data, it does not affect the structure of the hash table

Topic Five: design RandomPool structure

  • The expression Title: design a structure has the following three functions in this configuration, the required time complexity O (1):
    • insert (key): the addition of a key to the structure, do not repeat added
    • delete (key): remove the original structure of a key
    • getRandom (): returns the probability of any other key configuration
  • Thinking
    • Direct can be completed with a hash table, the difficulty is that (there getRandom under delete case)
    • Provided two hash table, a hash table key is first added value, value is the number of added; the second hash table key is added to the first of several, value is added to the value of
    • Setting a variable index, int index = 0, each of a join key, index ++
    • insert and delete can be done directly in the first hash table, the hash table also corresponds to the second operation make the same
    • getRandom direct random function generates a random number, but the problem is to delete might make value becomes discontinuous (the first of several to join), making it impossible to use random function
    • solve:
      • Whenever a delete key, let inedx--, let the key at index (ie, the last added key), covering the key out to be deleted, you want to delete the original value unchanged, the last added key / value line deleted.
      • In this way you can make value is a continuous value can be directly used random function random GET
        `` `
        public static class Pool { //K模板
        private HashMap<K, Integer> keyIndexMap;
        private HashMap<Integer, K> indexKeyMap;
        private int size;

      public Pool() {
      this.keyIndexMap = new HashMap<K, Integer>();
      this.indexKeyMap = new HashMap<Integer, K>();
      this.size = 0;
      }

      public void insert(K key) {
      if (!this.keyIndexMap.containsKey(key)) {
      this.keyIndexMap.put(key, this.size);
      this.indexKeyMap.put(this.size++, key);
      }
      }

      public void delete(K key) {
      if (this.keyIndexMap.containsKey(key)) {
      int deleteIndex = this.keyIndexMap.get(key);
      int lastIndex = --this.size;
      K lastKey = this.indexKeyMap.get(lastIndex);
      this.keyIndexMap.put(lastKey, deleteIndex);
      this.indexKeyMap.put(deleteIndex, lastKey);
      this.keyIndexMap.remove(key);
      this.indexKeyMap.remove(lastIndex);
      }
      }

      public K getRandom() {
      if (this.size == 0) {
      return null;
      }
      int randomIndex = (int) (Math.random() * this.size);
      return this.indexKeyMap.get(randomIndex);
      }

    }
    ```

To be continued

Guess you like

Origin www.cnblogs.com/ymjun/p/11700529.html
Recommended