数据结构是算法的基础,用好数据结构,算法实现更方便,代码更简洁。
涉及的数据结构:
上图来自:极客时间(覃超老师的算法课)
一、数组(Array)
int[][] nums = new int[][]{};
int[][] nums2 = new int[2][];
int[][] nums3 = {};
System.out.println("nums1 " + Arrays.toString(nums3));
System.out.println("nums2 " + Arrays.toString(nums3));
System.out.println("nums3 " + Arrays.toString(nums3));
二、Stack/Queue/Deque
Stack是继承自Vector,先进后出;
Queue是队列,Deque是双头队列,两者都是接口,Queue继承自Collection,Deque继承自Queue,LinkedList实现了Deque,Deque在Queue的基础上加了addFirst/offerFirst/...,removeLast/pollLast等方法;
Stack常用方法:
Stack<String> stack = new Stack<>(); // 初始化
stack.addAll(Arrays.asList("a", "b")); // 按照顺序添加
while (!stack.empty()) {
System.out.println(stack.pop()); // 按照先进后出顺序弹出
}
boolean isEmpty = stack.empty();
stack.push("first"); // 添加并返回添加的元素
String topPeek = stack.peek(); // 查看栈顶元素,不移除。如果为空,会抛出异常
String topPop = stack.pop(); // 移除栈顶元素。如果为空,会抛出异常
Queue常用方法:
Queue<String> queue = new LinkedList<>();
queue.addAll(Arrays.asList("a", "b"));
queue.offer("offer");
System.out.println(queue.element()); // 查看栈顶元素,不移除。如果为空,会抛出异常
while (!queue.isEmpty()) {
System.out.println(queue.poll()); // 移除栈顶元素。如果为空,不会抛出异常
}
Deque常用方法:
Deque<String> deque = new LinkedList<>();
deque.addAll(Arrays.asList("a", "b", "c"));
deque.offerFirst("e");
while (!deque.isEmpty()) {
System.out.println(deque.pollFirst());
System.out.println(deque.pollLast());
}