• lintcode--剑指offer---21--30道


    (21)Binary Tree Postorder Traversal

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param root: The root of binary tree.
    15      * @return: Postorder in ArrayList which contains node values.
    16      */
    17     public ArrayList<Integer> postorderTraversal(TreeNode root) {
    18         //1.边界判断
    19         ArrayList<Integer> arrList = new ArrayList<>();
    20         if (root == null) {
    21             return arrList;
    22         }
    23         //2.定义一个stack
    24         LinkedList<Integer> result = new LinkedList<>();
    25         Stack<TreeNode> stack = new Stack<>();
    26         stack.push(root);
    27         //3.循环体
    28         while (!stack.isEmpty()) {
    29             TreeNode cur = stack.pop();
    30             result.addFirst(cur.val); //关键代码:只有LinkedList才有addFirst这个操作
    31             if (cur.left != null) {
    32                 stack.push(cur.left);
    33             }
    34             if (cur.right != null) {
    35                 stack.push(cur.right);
    36             }
    37         }
    38         for (int i = 0; i < result.size(); i++) {
    39             arrList.add(result.get(i));
    40         }
    41         return arrList;
    42     }
    43 }
    View Code

     Binary Tree Preorder Traversal(补充)

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param root: The root of binary tree.
    15      * @return: Preorder in ArrayList which contains node values.
    16      */
    17     public ArrayList<Integer> preorderTraversal(TreeNode root) {
    18         //1.进行边界判断
    19         ArrayList<Integer> arrList = new ArrayList<>();
    20         if (root == null) {
    21             return arrList;
    22         }
    23         //2.根据题目要求定义stack或者queue
    24         Stack<TreeNode> stack = new Stack<>();
    25         stack.push(root);
    26         //3.开始进行循环
    27         while (!stack.isEmpty()) {
    28             TreeNode head = stack.pop();
    29             arrList.add(head.val);
    30             if (head.right != null) {
    31                 stack.push(head.right);
    32             }
    33             if (head.left != null) {
    34                 stack.push(head.left);
    35             }
    36         }
    37         return arrList;
    38     }
    39 }
    View Code

    Binary Tree Inorder Traversal(补充)

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param root: The root of binary tree.
    15      * @return: Inorder in ArrayList which contains node values.
    16      */
    17     public ArrayList<Integer> inorderTraversal(TreeNode root) {
    18         //1.边界判断
    19         ArrayList<Integer> arrList = new ArrayList<>();
    20         if (root == null) {
    21             return arrList;
    22         }
    23         //2.定义一个stack
    24         Stack<TreeNode> stack = new Stack<>();
    25         TreeNode cur = root;
    26         //3.循环体
    27         while (cur != null || !stack.isEmpty()) {
    28             while (cur != null) {
    29                 stack.push(cur);
    30                 cur = cur.left;
    31             }
    32             cur = stack.pop();
    33             arrList.add(cur.val);
    34             cur = cur.right;
    35         }
    36         return arrList;
    37     }
    38 }
    View Code

     (22)Copy List with Random Pointer

     1 /**
     2  * Definition for singly-linked list with a random pointer.
     3  * class RandomListNode {
     4  *     int label;
     5  *     RandomListNode next, random;
     6  *     RandomListNode(int x) { this.label = x; }
     7  * };
     8  */
     9 public class Solution {
    10     /**
    11      * @param head: The head of linked list with a random pointer.
    12      * @return: A new head of a deep copy of the list.
    13      */
    14     public RandomListNode copyRandomList(RandomListNode head) {
    15         if (head == null) {
    16             return null;
    17         }
    18         cloneNodes(head);
    19         cloneRandomPointer(head);
    20         return splitList(head);
    21     }
    22     //1.将所有节点复制并置于节点后面
    23     public void cloneNodes(RandomListNode head) {
    24         RandomListNode cur = head;
    25         while (cur != null) {
    26             //初始化cloned
    27             RandomListNode cloned = new RandomListNode(cur.label);
    28             cloned.label = cur.label;
    29             cloned.next = cur.next;
    30             cloned.random = null;
    31             //将指针连起来
    32             cur.next = cloned;
    33             cur = cloned.next;
    34         }
    35     }
    36     //2.复制所有的random指针
    37     public void cloneRandomPointer(RandomListNode head) {
    38         RandomListNode cur = head;
    39         while (cur != null) {
    40             RandomListNode cloned = cur.next;
    41             if (cur.random != null) {
    42                 cloned.random = cur.random.next;
    43             }
    44             cur = cloned.next;
    45         }
    46     }
    47     //3.将两个链表分开
    48     public RandomListNode splitList(RandomListNode head) {
    49         RandomListNode cur = head;
    50         RandomListNode clonedHead = null;
    51         RandomListNode clonedCur = null;
    52         //保存头结点并将指针移动一次
    53         clonedHead = cur.next;
    54         clonedCur = cur.next;
    55         cur.next = clonedCur.next;
    56         cur = cur.next;
    57         //循环体
    58         while (cur != null) {
    59             clonedCur.next = cur.next;
    60             clonedCur = clonedCur.next;
    61             cur.next = clonedCur.next;
    62             cur = cur.next;
    63         }
    64         return clonedHead;
    65     }
    66 }
    View Code

    (23)Spiral Matrix

     1 public class Solution {
     2     /**
     3      * @param matrix a matrix of m x n elements
     4      * @return an integer list
     5      */
     6     public List<Integer> spiralOrder(int[][] matrix) {
     7         List<Integer> list = new ArrayList<>();
     8         if (matrix == null || matrix.length == 0) {
     9             return list;
    10         }
    11         int rows = matrix.length;
    12         int columns = matrix[0].length;
    13         int start = 0;
    14         while (rows > start * 2 && columns > start * 2) {
    15             int endX = columns - start - 1;
    16             int endY = rows - start - 1;
    17             for (int i = start; i <= endX; i++) { //第一步肯定是要进行的
    18                 list.add(matrix[start][i]);
    19             }
    20             if (endY > start) { //判断是否进行第二步(第二步不进行,则不进行第三步,以下同理)
    21                 for (int i = start + 1; i <= endY; i++) {
    22                     list.add(matrix[i][endX]);
    23                 }
    24                 if (endX > start) { //判断第三步
    25                     for (int i = endX - 1; i >= start; i--) {
    26                         list.add(matrix[endY][i]);
    27                     }
    28                     if (endY > start + 1) { // 判断第四步
    29                         for (int i = endY - 1; i > start; i--) {
    30                             list.add(matrix[i][start]);
    31                         }
    32                     }
    33                 }
    34             }
    35             start++;
    36         }
    37         return list;
    38     }
    39 }
    View Code

    (24)Min Stack

     1 public class MinStack {
     2     //定义两个栈,分别保存栈的数据以及栈中的最小元素
     3     private Stack<Integer> stack;
     4     private Stack<Integer> minStack;
     5     public MinStack() {
     6         //初始化
     7         stack = new Stack<Integer>();
     8         minStack = new Stack<Integer>();
     9     }
    10 
    11     // public void push(int number) { //push version1
    12     //     stack.push(number);
    13     //     if (minStack.size() == 0 || minStack.peek() > number) {
    14     //         minStack.push(number);
    15     //     } else {
    16     //         minStack.push(minStack.peek());
    17     //     }
    18     // }
    19     
    20     public void push(int number) { //push version2
    21         stack.push(number);
    22         if (minStack.isEmpty()) {
    23             minStack.push(number);
    24         } else {
    25             minStack.push(Math.min(number, minStack.peek()));
    26         }
    27     }
    28 
    29     public int pop() {
    30         minStack.pop();
    31         return stack.pop();
    32     }
    33 
    34     public int min() {
    35         return minStack.peek();
    36     }
    37 }
    View Code

    (25)Convert Binary Search Tree to Doubly Linked List

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  * Definition for Doubly-ListNode.
    12  * public class DoublyListNode {
    13  *     int val;
    14  *     DoublyListNode next, prev;
    15  *     DoublyListNode(int val) {
    16  *         this.val = val;
    17  *         this.next = this.prev = null;
    18  *     }
    19  * }
    20  */
    21 public class Solution {
    22     /**
    23      * @param root: The root of tree
    24      * @return: the head of doubly list node
    25      */
    26     class ConnectType { //一个双链表的起点和终点
    27         DoublyListNode first;
    28         DoublyListNode last;
    29         public ConnectType(DoublyListNode first, DoublyListNode last) {
    30             this.first = first;
    31             this.last = last;
    32         }
    33     }
    34     public DoublyListNode bstToDoublyList(TreeNode root) {
    35         if (root == null) { //两个函数中的边界判断代表的意思不一样,因此不能删除任何一个
    36             return null;
    37         }
    38         ConnectType result = dfsHelper(root);
    39         return result.first;
    40     }
    41     public ConnectType dfsHelper(TreeNode root) { //获取一个树转化为双链表的起点和终点
    42         if (root == null) {
    43             return null;
    44         }
    45         ConnectType left = dfsHelper(root.left); //代表左子树转化为双链表,参数有起点和终点
    46         ConnectType right = dfsHelper(root.right); //代表右子树转化为双链表,参数有起点和终点
    47         //node代表此时的根节点
    48         DoublyListNode node = new DoublyListNode(root.val);
    49         ConnectType result = new ConnectType(null, null);
    50         if (left == null) {
    51             result.first = node;
    52         } else {
    53             //返回起点
    54             result.first = left.first;
    55             //建立双链
    56             left.last.next = node;
    57             node.prev = left.last;
    58         }
    59         if (right == null) {
    60             result.last = node;
    61         } else {
    62             //返回终点
    63             result.last = right.last;
    64             //建立双链
    65             right.first.prev = node;
    66             node.next = right.first;
    67         }
    68         return result;
    69     }
    70 }
    View Code

    (26)Majority Number

     1 public class Solution {
     2     /**
     3      * @param nums: a list of integers
     4      * @return: find a  majority number
     5      */
     6     public int majorityNumber(ArrayList<Integer> nums) {
     7         //整体思路:用count记录次数,用number记录当前的数字,对数组进行遍历,
     8         //如果跟number相同,count就加1.如果不同count减1,由于要找的数字次数大于一半,也就大于其他所有数字的次数之和,那么最后保存的数字必然就是要找的数字。
     9         if (nums == null || nums.size() == 0) {
    10             return 0;
    11         }
    12         int count = 0; //用于保存次数
    13         int number = 0; //用于保存当前的数字
    14         for (int i = 0; i < nums.size(); i++) {
    15             if (count == 0) {
    16                 number = nums.get(i);
    17             }
    18             if (nums.get(i) == number) {
    19                 count++;
    20             } else {
    21                 count--;
    22             }
    23         }
    24         return number;
    25     }
    26 }
    View Code

     1 public class Solution {
     2     /**
     3      * @param nums: a list of integers
     4      * @return: find a  majority number
     5      */
     6     public int majorityNumber(ArrayList<Integer> nums) {
     7         //整体思路:用count记录次数,用number记录当前的数字,对数组进行遍历,
     8         //如果跟number相同,count就加1.如果不同count减1,由于要找的数字次数大于一半,也就大于其他所有数字的次数之和,那么最后保存的数字必然就是要找的数字。
     9         if (nums == null || nums.size() == 0) {
    10             return 0;
    11         }
    12         int count = 0; //用于保存次数
    13         int number = 0; //用于保存当前的数字
    14         for (int i = 0; i < nums.size(); i++) {
    15             if (count == 0) {
    16                 number = nums.get(i);
    17             }
    18             if (nums.get(i) == number) {
    19                 count++;
    20             } else {
    21                 count--;
    22             }
    23             if (count == 0) {
    24                 number = nums.get(i);
    25             }
    26         }
    27         return number;
    28     }
    29 }

    (27)Maximum Subarray

     1 public class Solution {
     2     /**
     3      * @param nums: A list of integers
     4      * @return: A integer indicate the sum of max subarray
     5      */
     6     public int maxSubArray(int[] nums) {
     7         if (nums == null || nums.length == 0) {
     8             return 0;
     9         }
    10         int curSum = 0; //用于记录当前的总和
    11         int maxSum = nums[0]; //用于记录最大的和
    12         for (int i = 0; i < nums.length; i++) {
    13             if (curSum <= 0) { //如果当前的和为负的,则从下一个数重新加
    14                 curSum = nums[i];
    15             } else {
    16                 curSum += nums[i];
    17             }
    18             if (curSum > maxSum) {
    19                 maxSum = curSum;
    20             }
    21         }
    22         return maxSum;
    23     }
    24 }
    View Code
     

    (28)Spiral Matrix II

     1 public class Solution {
     2     /**
     3      * @param n an integer
     4      * @return a square matrix
     5      */
     6     public int[][] generateMatrix(int n) {
     7         if (n <= 0) {
     8             return new int[0][0];
     9         }
    10         int[][] result = new int[n][n];
    11         int number = 1;
    12         int start = 0; //由于是正方形的矩阵,所以只需要一个start
    13         while (n > 0) {
    14             for (int i = start; i < n; i++) {
    15                 result[start][i] = number++;
    16             }
    17             if (n - start >= 2) { //这句判断很重要,同Spiral Matrix这个程序一样,第一步必要做,但是后面的需要判断
    18                 for (int i = start + 1; i < n - 1; i++) {
    19                     result[i][n - 1] = number++;
    20                 }
    21                 for (int i = n - 1; i >= start; i--) {
    22                     result[n - 1][i] = number++;
    23                 }
    24                 for (int i = n - 2; i > start; i--) {
    25                     result[i][start] = number++;
    26                 }
    27             }
    28             n = n - 1;
    29             start++;
    30         }
    31         return result;
    32     }
    33 }
    View Code

     (29)Intersection of Two Linked Lists

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param headA: the first list
    15      * @param headB: the second list
    16      * @return: a ListNode
    17      */
    18     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    19         //整体思路:首先获得两个链表的长度,然后将长的链表遍历到跟短的一样,然后两个链表同时遍历,找到共同的节点
    20         if (headA == null || headB == null) {
    21             return null;
    22         }
    23         int aLen = getListLength(headA);
    24         int bLen = getListLength(headB);
    25         ListNode aCur = headA;
    26         ListNode bCur = headB;
    27         if (aLen > bLen) {
    28             for (int i = 0; i < aLen - bLen; i++) {
    29                 aCur = aCur.next;
    30             }
    31         } else {
    32             for (int i = 0; i < bLen - aLen; i++) {
    33                 bCur = bCur.next;
    34             }
    35         }
    36         while (aCur != null) {
    37             if (aCur.val == bCur.val && aCur.next == bCur.next) {
    38                 return aCur;
    39             }
    40             aCur = aCur.next;
    41             bCur = bCur.next;
    42         }
    43         return null;
    44     }
    45     public int getListLength(ListNode head) {
    46         if (head == null) {
    47             return 0;
    48         }
    49         int len = 0;
    50         while (head != null) {
    51             head = head.next;
    52             len++;
    53         }
    54         return len;
    55     }
    56 }
    View Code

     (30)Ugly Number II

     1 class Solution {
     2     /**
     3      * @param n an integer
     4      * @return the nth prime number as description.
     5      */
     6     public int nthUglyNumber(int n) {
     7         //思路:丑数必然是前面的丑数乘以2,3,5的结果,那么下一个丑数必然是之前的丑数
     8         //乘以2,3,5中的最小数
     9         if (n <= 0) {
    10             return 0;
    11         }
    12         //保存排序好的丑数
    13         List<Integer> arrList = new ArrayList<>();
    14         arrList.add(1);
    15         //p2,p3,p5的位置为它所在位置的丑数乘以2,3,5第一次大于当前的最大丑数
    16         int p2 = 0;
    17         int p3 = 0;
    18         int p5 = 0;
    19         //
    20         for (int i = 1; i < n; i++) {
    21             int lastUglyNum = arrList.get(i - 1);
    22             while (arrList.get(p2) * 2 <= lastUglyNum) {
    23                 p2++;
    24             }
    25             while (arrList.get(p3) * 3 <= lastUglyNum) {
    26                 p3++;
    27             }
    28             while (arrList.get(p5) * 5 <= lastUglyNum) {
    29                 p5++;
    30             }
    31             arrList.add(Math.min(arrList.get(p2) * 2, Math.min(arrList.get(p3) * 3, arrList.get(p5) * 5)));
    32         }
    33         return arrList.get(n - 1);
    34     }
    35 };
    View Code

    Ugly Number

     1 public class Solution {
     2     /**
     3      * @param num an integer
     4      * @return true if num is an ugly number or false
     5      */
     6     public boolean isUgly(int num) {
     7         if (num < 1) {
     8             return false;
     9         }
    10         while (num % 2 == 0) {
    11             num = num / 2;
    12         }
    13         while (num % 3 == 0) {
    14             num = num / 3;
    15         }
    16         while (num % 5 == 0) {
    17             num = num / 5;
    18         }
    19         if (num == 1) {
    20             return true;
    21         }
    22         return false;
    23     }
    24 }
    View Code
  • 相关阅读:
    纯JS实现中国行政区域上下联动选择地址
    java解析中国行政区域并在页面显示实现动态逐级筛选
    使用HttpClient 发送get、post请求,及其解析xml返回数据
    JS实现动态提示文本框可输入剩余字数(类似发表微博数字提示)
    webApi 数据绑定 获取
    EF Code First 常用命令
    [解决WebClient或HttpWebRequest首次连接缓慢问题]
    【转】Entity Framework技术系列之7:LINQ to Entities
    Ajax方法提交整个表单的信息
    【转】MVC中处理Json和JS中处理Json对象
  • 原文地址:https://www.cnblogs.com/muziyueyueniao/p/6862338.html
Copyright © 2020-2023  润新知