Skip to main content

2 posts tagged with "divideAndConquer"

View All Tags

· One min read

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

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 {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function (nums) {
if (nums.length === 0) {
return null;
}
return createBST(nums, 0, nums.length - 1);
};

const createBST = (nums, low, high) => {
if (low > high) {
return null;
}

let mid = Math.floor((high + low) / 2);

let node = new TreeNode(nums[mid]);
node.left = createBST(nums, low, mid - 1);
node.right = createBST(nums, mid + 1, high);
return node;
};

· One min read

https://leetcode.com/problems/majority-element/

Solution 1

/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
const element = {};

for (const num of nums) {
if (element[num]) {
element[num]++;
} else {
element[num] = 1;
}
}

let max = 0;
let targetNum = '';

for (let e in element) {
if (element[e] > max) {
max = element[e];
targetNum = e;
}
}

return Number(targetNum);
};