LeetCode TIL 241208

두선아 Dusuna·2024년 12월 8일

algorithm

목록 보기
2/14

Try to solve problems in JavaScript, Python, and Java.
This is TIL(memo of key learnings) for solving problems in these languages,
but mostly python.


Solved Problems 📝

241205:
1. 0101-symmetric-tree
2. 0102-binary-tree-level-order-traversal


Key Learnings 🤔

How to null None check with a tree node in python?

Easy, you can check if a current node is None.

if treeNode is None:

How can I ensure array[index] exists? before appending a value in python?

binary-tree-level-order-traversal

When working with a 2-dimensional array, attempting to append a value to a non-existent index results in an error.

To avoid this, you can check the length📏 of the array to ensure the target(array[index]) index exists.

# Case: 'level' represents the depth of the binary tree node.
result = []
...
if len(result) <= level:
    result.append([])  # add a new list for the current level.

result[level].append(node.val)

How can I declare a variable with nested array types in java?

  • List<List<Integer>>
List<List<Integer>> nestedList = new ArrayList<>();

What Is the Difference Between List<int> and int[] in Java?

Aspectint[]List<Integer>
SizeFixedDynamic
TypePrimitive intWrapper Integer
MemoryMore efficient (no object overhead)Higher (due to object overhead)
PerformanceFasterSlower (boxing/unboxing)
ResizingNot resizableResizable

Why use new ArrayList<>(), not [] in java?

In Java, List is an interface, so you cannot directly instantiate it!
must use a concrete implementation like ArrayList, [] is not a valid way.

List<List<Integer>> result = new ArrayList<>();

What Is ArrayList?

ArrayList is a dynamic array implementation of the List interface in Java, provided by the java.util package.

Boxing and unboxing

Boxing and Unboxing refer to the automatic conversion between primitive types and corresponding wrapper class objects.

Add a slight overhead because the Java Virtual Machine (JVM), create new objects for primitive values & convert objects back into primitives.

int num = 5;
Integer boxedNum = num;  // Automatic boxing
int unboxNum = boxedNum;  // Automatic unboxing

boxing

  • The process of converting a primitive type into its corresponding wrapper class object.(int 👉 integer)
  • store primitive values in collections like List<Integer>
  • collections cannot store primitive types (only objects).

unboxing

  • converting an object of a wrapper class.
  • happens when you perform operations that require primitive types
profile
안녕하세요.

0개의 댓글