剑指 Offer 66. 构建乘积数组image.png

  1. class Solution {
  2. public int[] constructArr(int[] a) {
  3. int len = a.length;
  4. int[] arr = new int[len];
  5. if(len==0)
  6. return arr;
  7. arr[0] = 1;
  8. int t = a[0];
  9. for(int i = 1; i < len; i++) {
  10. arr[i] = t;
  11. t*=a[i];
  12. }
  13. System.out.println(Arrays.toString(arr));
  14. t = a[len-1];
  15. for(int i = len-2;i>=0;i--) {
  16. arr[i] *= t;
  17. t *= a[i];
  18. }
  19. System.out.println(Arrays.toString(arr));
  20. return arr;
  21. }
  22. }

剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

image.png

  1. class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. if(root==null)
  4. return null;
  5. int min = Math.min(p.val,q.val);
  6. int max = Math.max(p.val,q.val);
  7. if(root.val==min || root.val==max)
  8. return root;
  9. if(root.val >min && root.val < max )
  10. return root;
  11. if(root.val > min && root.val > max)
  12. return lowestCommonAncestor(root.left,p,q);
  13. if(root.val<max && root.val<min)
  14. return lowestCommonAncestor(root.right,p,q);
  15. return null;
  16. }
  17. }

剑指 Offer 68 - II. 二叉树的最近公共祖先

image.png

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  12. return find(p,q,root);
  13. }
  14. TreeNode find(TreeNode p,TreeNode q,TreeNode root) {
  15. if(root==null)
  16. return null;
  17. TreeNode l = find(p,q,root.left);
  18. TreeNode r = find(p,q,root.right);
  19. if(l!=null && r!=null){
  20. return root;
  21. }
  22. if(root==q || root==p) {
  23. if(l!=null || r!=null)
  24. return root;
  25. return root;
  26. }
  27. if(l!=null)
  28. return l;
  29. if(r!=null)
  30. return r;
  31. return null;
  32. }
  33. }

剑指 Offer 60. n个骰子的点数

image.png

dp[i][j] 表示一共i个筛子,掷出j点数的次数
第i个筛子可以是1,2,3,4,5,6 ,所以dp[i][j] = dp[i-1][j-1] + dp[i-1][j-2] + dp[i-1][j-3] + dp[i-1][j-4] + ..dp[i-1][j-6]

  1. class Solution {
  2. public double[] dicesProbability(int n) {
  3. int[][] dp = new int[n+1][6*n+1];
  4. for(int i = 1; i <= 6; i++) {
  5. dp[1][i]=1;
  6. }
  7. for(int i = 2; i <= n ;i++) {
  8. for(int j = i;j<=6*i;j++) {
  9. for(int k = 1; k <= 6 && k<j ;k++) {
  10. dp[i][j] += dp[i-1][j-k];
  11. }
  12. }
  13. }
  14. double count = 0;
  15. for(int i = n;i<=6*n;i++) {
  16. count+=dp[n][i];
  17. }
  18. double[] res = new double[6*n-n+1];
  19. for(int i = 0 ; i < res.length; i++) {
  20. res[i] = dp[n][i+n]/count;
  21. }
  22. return res;
  23. }
  24. }

剑指 Offer 62. 圆圈中最后剩下的数字

image.png

  1. class Solution {
  2. public int lastRemaining(int n, int m) {
  3. int f = 0;
  4. for(int i = 2; i <= n; i++) {
  5. f = (m+f)%i;
  6. }
  7. return f;
  8. }
  9. }