Skip to main content

59 posts tagged with "easy"

View All Tags

· One min read

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Solution 1

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
if (!head) {
return null;
}

let curr = head;
let next = head.next;

while (next) {
if (curr.val === next.val) {
curr.next = next.next;
} else {
curr = curr.next;
}
next = next.next;
}

return head;
};

· 2 min read

https://leetcode.com/problems/merge-sorted-array/

Solution 1

/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function (nums1, m, nums2, n) {
while (n > 0) {
// 뒤에서 부터 도는게 핵심

if (nums1[m - 1] > nums2[n - 1]) {
// nums1이 nums2보다 클 경우, nums1의 자리를 뒤로 배치
nums1[m + n - 1] = nums1[m - 1];
m--;
} else {
// nums1이 nums2보다 작을 경우, nums1의 자리에 num2 배치
nums1[m + n - 1] = nums2[n - 1];
n--;
}
}
};

아래처럼 알고리즘이 돌아감

const nums1 = [4, 5, 6, 0, 0, 0];
const m = 3;
const nums2 = [1, 2, 3];
const n = 3;

merge(nums1, m, num2, n);

// 풀이
// [4, 5, 6, 0, 0, 6]
// [4, 5, 6, 0, 5, 6]
// [4, 5, 6, 4, 5, 6]
// [4, 5, 3, 4, 5, 6]
// [4, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]

· One min read

https://leetcode.com/problems/binary-tree-inorder-traversal/

Solution 1

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
let stack = [];
let result = [];

while (root !== null || stack.length !== 0) {
while (root !== null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
result.push(root.val);
root = root.right;
}
return result;
};