[2016/06/24] LeetCode / Java - Day 02 -

来源:互联网 发布:多益网络 编辑:程序博客网 时间:2024/05/30 05:13

258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Hint:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?
  2. What are all the possible results?
  3. How do they occur, periodically or randomly?
  4. You may find this Wikipedia article useful.

思路:一道涨姿势的题目。。直接运用https://en.wikipedia.org/wiki/Digital_root里的结论即可。

public class Solution {    public static int addDigits(int num) {        return (num-9*((num-1)/9));            }}

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路:嗯,总算是没有白看数据结构。。一开始拿到这道题我是懵逼的,但是仔细想了想。。试了试。。就出来了(惊呆。我得说AC的时候我是很意外的→ →思路很简单,就是递归,然后比较一下递归回来的左子树和右子树哪个深度大,就采用哪个。。然后不要忘了空树的深度是0.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public static int maxDepth(TreeNode root) {    if(root == null) return 0;    int maxl= 1;    int maxr=1;    if(root.left!=null)    {    maxl =1 + maxDepth(root.left);    }    if (root.right != null){    maxr = 1 + maxDepth(root.right);    }        return maxl>maxr?maxl:maxr;            }    }

136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

【思路】这个我是真的想不到。。。想到用XOR的人真是神人。。。
public class Solution {    public static int singleNumber(int[] nums) {    int m=0;    for(int i=0; i<nums.length;i++){    m=m^nums[i];    }return m;            }}


0 0