LeetCode 102_104_111_22_69_208_191_338_231

102. Binary Tree Level Order Traversal

在这里插入图片描述
BFS iterative:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> temp =new LinkedList<TreeNode>();
        List<List<Integer>> result =new LinkedList <List<Integer>>();
        if(root==null) return result;
        temp.offer(root);
        while(!temp.isEmpty()){
            int length=temp.size(); //先求出队列的size,不要放在for循环里面,长度会变!!!
            List<Integer> sub =new LinkedList<Integer>();
            for(int i=0;i<length;i++){
                if(temp.peek().left!=null) temp.offer(temp.peek().left);
                if(temp.peek().right!=null) temp.offer(temp.peek().right);
                sub.add(temp.poll().val);
            }
            result.add(sub);
        }
        return result;
        
    }
}

在这里插入图片描述
DFS recursive:O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result =new LinkedList<>();
        helper(result,root,0);
        return result;
        
    }
    public void helper(List<List<Integer>> result,TreeNode root,int level){
        if(root==null) return;
        if(level>=result.size())
            result.add(new LinkedList<>());
        result.get(level).add(root.val);
        helper(result,root.left,level+1);
        helper(result,root.right,level+1);
    }
}

在这里插入图片描述

104. Maximum Depth of Binary Tree

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        return 1+ Math.max(maxDepth(root.left),maxDepth(root.right));
        
    }
}

BFS:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        int count=0;
        Queue<TreeNode> queue =new LinkedList<>();
        queue.offer(root);
        
        while(!queue.isEmpty()){
            int length=queue.size();
            for(int i=0;i<length;i++){
                TreeNode node =queue.poll();
                
                if(node.left!=null){
                   queue.offer(node.left); 
                }
                
                if(node.right!=null){
                   queue.offer(node.right); 
                }
                
            }
            count++;
        }
        
        return count;
        
    }
}

DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        int max=0,temp;
        Stack<TreeNode> treenode =new Stack<>();
        Stack<Integer> value =new Stack<>();
        treenode.push(root);
        value.push(1);
        
        while(!treenode.empty()){
            
            TreeNode node =treenode.pop();
            temp=value.pop();
            max=Math.max(max,temp);
            
            if(node.left!=null){
                treenode.push(node.left);
                value.push(temp+1);
            }
            
            if(node.right!=null){
                treenode.push(node.right);
                value.push(temp+1);
            }
            
        }
        
        return max;
        
    }
}

111. Minimum Depth of Binary Tree

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        int left=minDepth(root.left);
        int right =minDepth(root.right);
        return (left==0||right==0)?left+right+1:Math.min(left,right)+1;
        
    }
}

BFS:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//BFS
class Solution {
    public int minDepth(TreeNode root) {
        if(root==null )return 0;
        Queue<TreeNode> queue =new LinkedList<>();
        queue.offer(root);
        int depth=1;
        
        while(!queue.isEmpty()){
            
            int length=queue.size();
            
            for(int i=0;i<length;i++){
                TreeNode node =queue.poll();
                if(node.left==null&&node.right==null){
                    return depth;
                }
                if(node.left!=null){
                    queue.offer(node.left);
                    
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }
            }
            
            depth++;           
        }
        return depth;
        
    }
}

DFS:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if(root==null ) return 0;
        if(root.left!=null&&root.right!=null)
            return Math.min(minDepth(root.left),minDepth(root.right))+1;
        else
            return Math.max(minDepth(root.left),minDepth(root.right))+1;
        
    }
}

22. Generate Parentheses

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
两道数独,两道N皇后

69. Sqrt(x)

在这里插入图片描述
二分法:

class Solution {
    public int mySqrt(int x) {     //二分法
        if(x==0||x==1) return x;
        int left=0,right=x;
        while(true){   //这里要用true,不能用left<=right,否则要在后面有返回值
            int mid=left+(right-left)/2;
            if(mid>x/mid) right=mid-1;
            else{
                if((mid+1)>x/(mid+1)) return mid;
                left=mid+1;
            }
        }
        
        
    }
}
class Solution {
    public int mySqrt(int x) {     //牛顿法
        if(x==0||x==1) return x;
        double oldres=x;
        double newres=0;
        double temp;
        while(Math.abs(oldres-newres)>0.01){
            temp=(oldres+x/oldres)/2;
            newres=oldres;
            oldres=temp;
        }
        return (int) oldres;
        
        
    }
}

208. Implement Trie (Prefix Tree)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

public class TrieNode{
    public char val;
    public boolean isWord;
    public TrieNode[] children =new TrieNode[26];
    public TrieNode(){};
    TrieNode(char c){
        TrieNode node=new TrieNode();
        node.val =c;
    }
    
}
class Trie {
    private TrieNode root;

    /** Initialize your data structure here. */                                  
    public Trie() {
        root=new TrieNode();
        root.val=' ';
        
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode ws=root;
        
        for(int i=0;i<word.length();i++){
            char c=word.charAt(i);
            if(ws.children[c-'a']==null){
                ws.children[c-'a']=new TrieNode(c);
            }
            ws=ws.children[c-'a'];
        }
        
        ws.isWord=true;
        
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode ws=root;
        for(int i=0;i<word.length();i++){
            char c=word.charAt(i);
            if(ws.children[c-'a']==null) return false;
            ws=ws.children[c-'a'];
        }
        return ws.isWord;
        
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode ws=root;
        for(int i=0;i<prefix.length();i++){
            char c=prefix.charAt(i);
            if(ws.children[c-'a']==null) return false;
            ws=ws.children[c-'a'];
        }
        return true;
        
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

212. Word Search II

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

191. Number of 1 Bits

在这里插入图片描述

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count=0;
        for(int i=0;i<32;i++){
            if(n%2!=0) count++;
            n= n>>1;    
        }


        return count;
        
    }
}
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count=0;
        while(n!=0){
            n=n&(n-1);
            count++;
        }
        return count;
        
    }
}

338. Counting Bits

在这里插入图片描述

class Solution {
    public int[] countBits(int num) {
        
        int[] count=new int[num+1];
        count[0]=0;
        for(int i=1;i<=num;i++){
            count[i]=count[i&(i-1)]+1;
            
        }
        return count;
    }
}

class Solution {
    public int[] countBits(int num) {
        
        int[] count=new int[num+1];
        for(int i=1;i<=num;i++){
            int temp=i;
            while(temp!=0){
                if(temp%2==1) count[i]++;
                temp=temp>>1;
            }

            
        }
        return count;
    }
}

231. Power of Two

在这里插入图片描述

class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n<=0) return false;
        int count=0;
        while(n!=0){
            n=n&(n-1);
            count++;
        }
        if(count==1) return true;
        return false;
        
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目描述: 给定一个字符串,请将字符串里的字符按照出现的频率降序排列。 示例 1: 输入: "tree" 输出: "eert" 解释: 'e'出现两次,'r'和't'都只出现一次。因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。 示例 2: 输入: "cccaaa" 输出: "cccaaa" 解释: 'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。注意"cacaca"是不正确的,因为相同的字母必须放在一起。 示例 3: 输入: "Aabb" 输出: "bbAa" 解释: 此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。注意'A'和'a'被认为是两种不同的字符。 Java代码如下: ``` import java.util.*; public class Solution { public String frequencySort(String s) { if (s == null || s.length() == 0) { return ""; } Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); map.put(c, map.getOrDefault(c, 0) + 1); } List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); StringBuilder sb = new StringBuilder(); for (Map.Entry<Character, Integer> entry : list) { char c = entry.getKey(); int count = entry.getValue(); for (int i = 0; i < count; i++) { sb.append(c); } } return sb.toString(); } } ``` 解题思路: 首先遍历字符串,使用HashMap记录每个字符出现的次数。然后将HashMap转换为List,并按照出现次数从大到小进行排序。最后遍历排序后的List,将每个字符按照出现次数依次添加到StringBuilder中,并返回StringBuilder的字符串形式。 时间复杂度:O(nlogn),其中n为字符串s的长度。遍历字符串的时间复杂度为O(n),HashMap和List的操作时间复杂度均为O(n),排序时间复杂度为O(nlogn),StringBuilder操作时间复杂度为O(n)。因此总时间复杂度为O(nlogn)。 空间复杂度:O(n),其中n为字符串s的长度。HashMap和List的空间复杂度均为O(n),StringBuilder的空间复杂度也为O(n)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值