n个人围成一个圈,报数,k的倍数的人离开,求最后一个。
private static int removeNM(int n, int k) {
LinkedList<Integer> ll = new LinkedList<>();
for (int i = 1; i <= n; i++) {
ll.add(i);
}
int removed = -1;
while (ll.size() > 1) {
//计算下标,+m代表m的倍数,%代表控制在范围之中
removed = (removed + k) % ll.size();
//移除以后下标减一
ll.remove(removed--);
}
return ll.get(0);//返回剩下的元素
}跳n台阶问题:一次可以跳1-3级,求共有多少种跳法。
第一次跳的时候就有两种不同的选择,递归思想:一是第一次只跳1级,此时跳法数目等于后面剩下的n-1级台阶的跳法数目,即为f(n-1);另外一种选择是第一次跳2级,此时跳法数目等于后面剩下的n-2级台阶的跳法数目,即为f(n-2)…因此n级台阶时的不同跳法的总数f(n)=f(n-1)+f(n-2)
+f(n-3)。
private static int jump(int n) {
if (n == 1) {
return 1;
} else if (n == 2) {
return 2;
} else if (n == 3) {
return 4;
} else {
return jump(n - 1) + jump(n - 2) + jump(n - 3);
}
}动态规划、贪心算法的共性与区别
二叉树遍历,广度,深度,前中后序
import java.util.ArrayDeque;
public class BinaryTree {
static class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
TreeNode root;
public BinaryTree(int[] array) {
root = makeBinaryTreeByArray(array, 1);
}
/**
* 采用递归的方式创建一颗二叉树
* 传入的是二叉树的数组表示法
* 构造后是二叉树的二叉链表表示法
*/
public static TreeNode makeBinaryTreeByArray(int[] array, int index) {
if (index < array.length) {
int value = array[index];
if (value != 0) {
TreeNode t = new TreeNode(value);
array[index] = 0;
t.left = makeBinaryTreeByArray(array, index * 2);
t.right = makeBinaryTreeByArray(array, index * 2 + 1);
return t;
}
}
return null;
}
/**
* 深度优先遍历,相当于先根遍历
* 采用非递归实现
* 需要辅助数据结构:栈
*/
public void depthOrderTraversal() {
if (root == null) {
System.out.println("empty tree");
return;
}
ArrayDeque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.print(node.value + " ");
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
System.out.print("\n");
}
/**
* 广度优先遍历
* 采用非递归实现
* 需要辅助数据结构:队列
*/
public void levelOrderTraversal() {
if (root == null) {
System.out.println("empty tree");
return;
}
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.remove();
System.out.print(node.value + " ");
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
System.out.print("\n");
}
/**
* 13
* / \
* 65 5
* / \ \
* 97 25 37
* / /\ /
* 22 4 28 32
*/
public static void main(String[] args) {
int[] arr = {0, 13, 65, 5, 97, 25, 0, 37, 22, 0, 4, 28, 0, 0, 32, 0};
BinaryTree tree = new BinaryTree(arr);
tree.depthOrderTraversal();
tree.levelOrderTraversal();
}
}
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優(yōu)質文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦