Mock Interview: Microsoft

JJ·2021년 6월 17일
0

MockTest

목록 보기
34/60

1469. Find All The Lonely Nodes

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private List<Integer> result;
    public List<Integer> getLonelyNodes(TreeNode root) {
        result = new ArrayList<Integer>();
        
        helper(root);
        
        return result;
        
    }
    
    private void helper(TreeNode root) {
        if (root == null) {
            return;
        }
        
        if (root.left == null && root.right == null) {
            return;
        }
        
        if (root.left == null && root.right != null) {
            result.add(root.right.val);
            helper(root.right);
        } else if (root.right == null && root.left != null) {
            result.add(root.left.val);
            helper(root.left);
        } else {
            helper(root.left);
            helper(root.right);
        }
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Find All The Lonely Nodes.
Memory Usage: 39.8 MB, less than 47.70% of Java online submissions for Find All The Lonely Nodes.

재귀 이용~
트리 재귀가 이렇게만 나오면 얼마나 좋을까요^^

1381. Design a Stack With Increment Operation

class CustomStack {
    
    //private int start;
    private int end;
    private int msize;
    private int[] stack;

    public CustomStack(int maxSize) {
        stack = new int[maxSize];
        //start = 0;
        end = 0; 
        msize = maxSize;
    }
    
    public void push(int x) {
        if (end < msize) {
            stack[end++] = x;
        }
    }
    
    public int pop() {
        if (end == 0) {
            return -1;
        } else {
            end--;
            return stack[end];
        }
    }
    
    public void increment(int k, int val) {
        int num = Math.min(k, end);
        for (int i = 0; i < num; i++) {
            stack[i] = stack[i] + val;
        }
    }
}

/**
 * Your CustomStack object will be instantiated and called as such:
 * CustomStack obj = new CustomStack(maxSize);
 * obj.push(x);
 * int param_2 = obj.pop();
 * obj.increment(k,val);
 */

Runtime: 5 ms, faster than 80.09% of Java online submissions for Design a Stack With Increment Operation.
Memory Usage: 39.6 MB, less than 72.36% of Java online submissions for Design a Stack With Increment Operation.

ㅎㅏ....................
일단 바보처럼 뒤에만 잡으면 되는데 앞뒤 붙잡고 있었어요... stack인디....^^

그리고 마지막에 Math.min(k, end)를 Integer.min(k, numElements)로 하고 있었는데
이걸 못보고 계속 안돌아가서 범위 조절만 400년 했읍니다
인터뷰에서는 이런 실수 하지 않길...plz

0개의 댓글