美文网首页
Leetcode-Java(二十六)

Leetcode-Java(二十六)

作者: 文哥的学习日记 | 来源:发表于2018-06-20 23:54 被阅读37次

257. Binary Tree Paths

类似于分治法吧。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        if(root==null)
            return res;
        else{
            if(root.left == null && root.right == null)
                res.add(root.val+"");
            if(root.left!=null){
                List<String> left = binaryTreePaths(root.left);
                for(int i=0;i<left.size();i++){
                    res.add(root.val +"->" + left.get(i));
                }
            }

            if(root.right!=null){
                List<String> right = binaryTreePaths(root.right);
                for(int i=0;i<right.size();i++){
                    res.add(root.val +"->" + right.get(i));
                }
            }
        }
        return res; 
    }
}

258. Add Digits

小trick

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

260. Single Number III

既然有两个数只出现了一次,那么这两个数至少有一位不一样,即异或不为0,那么可以根据这一位将数据分为两组,每一组再根据lian ge

class Solution {
    public int[] singleNumber(int[] nums) {
        int res = 0;
        for(int num:nums){
            res ^= num;
        }
        int seperator = 1;
        while((seperator & res) == 0){
            seperator <<= 1;
        }
        int[] result = new int[2];
        for(int num:nums){
            if((num & seperator) == 0)
                result[0] ^= num;
            else
                result[1] ^= num;
        }
        return result;
    }
}

相关文章

  • Leetcode-Java(二十六)

    257. Binary Tree Paths 类似于分治法吧。 258. Add Digits 小trick 26...

  • leetcode 100

    github个人所有的leetcode题解,都在我的 leetcode-java,欢迎star和共同探讨。leet...

  • Leetcode-Java(三十)

    299. Bulls and Cows 一开始我用的是HashSet保存两个字符串中出现过的数字但是没有匹配上的,...

  • Leetcode-Java(十四)

    131. Palindrome Partitioning 回溯法 132. Palindrome Partitio...

  • Leetcode-Java(三十一)

    303. Range Sum Query - Immutable 用一个数组保存从0到当前位置的和。 304. R...

  • Leetcode-Java(二十二)

    211. Add and Search Word - Data structure design 建立一棵字典树,...

  • Leetcode-Java(二十三)

    221. Maximal Square 动态规划,只用一个一维数组,这里要注意代码里的对应关系,相当于在原数组的基...

  • Leetcode-Java(二十四)

    231. Power of Two 232. Implement Queue using Stacks 题目中要求...

  • Leetcode-Java(二十五)

    241. Different Ways to Add Parentheses 采用分治算法,分治算法的基本思想是将...

  • Leetcode-Java(二十七)

    263. Ugly Number 264. Ugly Number II 分析:这道题最直观地想法是暴力查找,但不...

网友评论

      本文标题:Leetcode-Java(二十六)

      本文链接:https://www.haomeiwen.com/subject/jyyfyftx.html