yeshaoting 写道
算法描述:
一个栈stack,具有push和pop操作,其时间复杂度皆为O(1)。
设计算法max操作,求栈中的最大值,该操作的时间复杂度也要求为O(1)。
可以修改栈的存储方式,push,pop的操作,但是要保证O(1)的时间复杂度,空间时间复杂度无要求。
思路:
我借助一个变量count和一个数组空间(其实就是一个栈)完成该时间复杂度为O(1)的算法设计。
这里面不需要用到快排吧。。那样的话还能叫o(1)?
贴上我的code:用了个最大栈保存添加路径上的最大值,删除的时候如果相等撤销最大值栈中的顶部元素即可。
另鄙视下,共享东西的时候都鼓掌叫好,求助发问就隐藏哦鄙视哦扣分哦臭鸡蛋烂白菜都来了。。。不多说了 果断以后文章只丢博客里
package sunfa;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Random;
public class LinkedListMaxVal<E> {
public static void main(String[] args) {
LinkedListMaxVal<Integer> stack = new LinkedListMaxVal<Integer>(
new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
Random ran = new Random();
for (int i = 1; i <= 20; i++) {
stack.push(ran.nextInt(100));
System.out.println(stack + "," + stack.max()+","+stack.maxStack);
if (i % 4 == 0) {
Integer ee = stack.peek();
System.out.println("=============>pop:"+ee+"," + stack + "," + stack.max()+","+stack.maxStack);
stack.pop();
}
}
System.out.println("pop all>>>>>>>>>>>>>------------------");
System.out.println("删除的元素 | 数据栈 | 最大值 | 最大值栈");
while(!stack.isEmpty()){
Integer ee = stack.peek();
System.out.println("pop:" +ee+","+ stack + "," + stack.max()+","+stack.maxStack);
stack.pop();
}
System.out.println("---end-----");
System.out.println(stack);
}
private Object[] item;
private int count;//栈内元素数目 ,栈顶元素索引为count-1
private LinkedList<E> maxStack = new LinkedList<E>();//最大值备用栈,为省事借用链表
private final String EMPTY_STACK_STR = "空栈";
private Comparator<E> comp;
public LinkedListMaxVal(Comparator<E> c) {
item = new Object[10];
comp = c;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
if (count + 1 == item.length)
item = Arrays.copyOf(item, item.length << 1);
item[count++] = e;
if (count == 1)
maxStack.push(e);
else {
if (compare(maxStack.peekFirst(), e) <= 0)//=号不要丢了,这很关键
maxStack.push(e);
}
}
public E pop() {
if (isEmpty())
throw new NullPointerException(EMPTY_STACK_STR);
E e = peek();
item[count - 1] = null;
if (count == 1)
maxStack.pop();
else {
if (compare(maxStack.peekFirst(), e) == 0)
maxStack.pop();
}
count--;
return e;
}
public E max() {
if (maxStack.isEmpty())
throw new NullPointerException(EMPTY_STACK_STR);
return maxStack.peekFirst();
}
public E peek() {
if (isEmpty())
throw new NullPointerException(EMPTY_STACK_STR);
return (E) item[count - 1];
}
private int compare(E e1, E e2) {
return comp != null ? (((comp).compare(e1, e2)))
: (((Comparable<E>) e1).compareTo(e2));
}
public boolean isEmpty() {
return count == 0;
}
public String toString() {
String s = "[";
for (int i = 0; i < item.length; i++) {
if (item[i] != null)
s += item[i] + ",";
}
if (s.length() == 1) {
s += "]";
} else {
s = s.substring(0, s.length() - 1) + "]";
}
return s;
}
}