目录

读完这个题第一时间我就想到了 HashMap, 我们把字符串变成字符数组, 把每一个字符放进 map 里面, 然后在遍历字符数组, 先碰到了value 值为 1 的字符马上返回, 没有就返回 1 就好了.
下面看代码:
- import java.util.Scanner;
- import java.util.HashMap;
- import java.util.Map;
-
- public class Main {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- while (scanner.hasNext()) {
- String str = scanner.nextLine();
- int result = firstUniqChar(str);
-
- if (result == -1) {
- System.out.println(result);
- } else {
- System.out.println((char)result);
- }
- }
- }
-
- private static int firstUniqChar(String str) {
- Map
map = new HashMap<>(); - for (char ch : str.toCharArray()) {
- map.put(ch, map.getOrDefault(ch, 0) + 1);
- }
- for (char ch : str.toCharArray()) {
- if (map.get(ch) == 1) {
- return ch;
- }
- }
- return -1;
- }
- }
可以看到也是通过了这个题


看到从尾到头反过来打印, 想到一种数据结构--栈, 栈的特点就是先进后出, 所以我们可以把链表的值, 从头节点开始, 全部压栈, 然后再全部弹出存放到数组中, 再输出就好了.
- public int[] reversePrint(ListNode head) {
- Stack
stack = new Stack<>(); - ListNode cur = head;
- while (cur != null) {
- stack.push(cur.val);
- cur = cur.next;
- }
-
- int[] arr = new int[stack.size()];
- for (int i = 0; i < arr.length; i++) {
- arr[i] = stack.pop();
- }
- return arr;
- }


将一个栈当作输入栈,用于压栈传数据, 另一个栈用于出栈, 弹出数据
每次出栈, 如果输出栈为空, 则将输入栈的全部数据依次弹出并压入输出栈, 这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序.
就很简单的push操作就正常push到第一个栈末尾, pop操作时,优先将第一个栈的元素弹出,并依次进入第二个栈中, 就好了.
- public class Solution {
- Stack
stack1 = new Stack(); - Stack
stack2 = new Stack(); -
- public void push(int node) {
- stack1.push(node);
- }
-
- public int pop() {
- while (!stack1.isEmpty()) {
- stack2.push(stack1.pop());
- }
- int res = stack2.pop();
- while (!stack2.isEmpty()) {
- stack1.push(stack2.pop());
- }
- return res;
- }
- }


从上向下打印, 也就是层序遍历打印, 这里又被称为 二叉树的广度优先搜索(BFS) , BFS 通常是借助 队列 先入先出的特点来实现的.
- public int[] levelOrder(TreeNode root) {
- List
list = new ArrayList<>(); - Deque
deque = new ArrayDeque<>(); -
- if (root != null) {
- deque.addLast(root);
- }
-
- while (!deque.isEmpty()) {
- TreeNode t = deque.pollFirst();
- list.add(t.val);
- if (t.left != null) {
- deque.addLast(t.left);
- }
- if (t.right != null) {
- deque.addLast(t.right);
- }
- }
-
- int n = list.size();
- int[] ans = new int[n];
- for (int i = 0; i < n; i++) {
- ans[i] = list.get(i);
- }
- return ans;
- }


采用递归的思想解题, 每次都用两个链表头部值较小的一个节点与剩下元素的 mergeTwoLists 操作结果合并。
- public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
- if (l1 == null) {
- return l2;
- }
- if (l2 == null) {
- return l1;
- }
-
- if (l1.val > l2.val) {
- l2.next = mergeTwoLists(l1, l2.next);
- return l2;
- } else {
- l1.next = mergeTwoLists(l1.next, l2);
- return l1;
- }
- }
