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

7 篇文章 0 订阅

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;
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值