Mock Interview: Facebook

JJ·2021년 7월 3일
0

MockTest

목록 보기
44/60

1662. Check If Two String Arrays are Equivalent

class Solution {
    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
        StringBuilder a1 = new StringBuilder();
        StringBuilder a2 = new StringBuilder();
        
        for (String w: word1) {
            a1.append(w);
        }
        
        for (String w2: word2) {
            a2.append(w2);
        }
        
        String r1 = a1.toString();
        String r2 = a2.toString();
        
        return (r1.equals(r2));

    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Check If Two String Arrays are Equivalent.
Memory Usage: 37.2 MB, less than 53.46% of Java online submissions for Check If Two String Arrays are Equivalent.

StringBuilder로 만들어준 다음에 비교해줬어요

236. Lowest Common Ancestor of a 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 TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        Queue<TreeNode> pfam = new LinkedList<TreeNode>();
        Queue<TreeNode> qfam = new LinkedList<TreeNode>();
        
        findFam(root, p, pfam);
        findFam(root, q, qfam);
        
        System.out.println(pfam);
        System.out.println(qfam);
        
        
        TreeNode lca = new TreeNode(-1); 
        while (pfam.peek() == qfam.peek()) {
            lca = pfam.remove();
            qfam.remove();
            
            if (lca == p || lca == q) {
                return lca;
            }
        }
        
        return lca;
        
        
    }
    
    
    private void findFam(TreeNode root, TreeNode target, Queue<TreeNode> fam) {
        if (root == null) {
            return;
        }
        
        if (root == target) {
            return;
        }
        
        fam.add(root.left);
        fam.add(root.right);
        findFam(root.left, target, fam);
        findFam(root.right, target, fam);
    }
}

Parent를 다 잡아준 뒤 최대한 뒤에 가서 리턴하려고 했는데 잘 안됐다는ㄴ점..

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q)  return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left != null && right != null)   return root;
        return left != null ? left : right;
    }
}

Runtime: 4 ms, faster than 100.00% of Java online submissions for Lowest Common Ancestor of a Binary Tree.
Memory Usage: 41.4 MB, less than 22.63% of Java online submissions for Lowest Common Ancestor of a Binary Tree.

저번에 베껴왔던 루션이는 엄청 길었던거 같은데 discussion을 보니깐 굉장히 짧네요..

0개의 댓글