MoreThanHalfNum
function MoreThanHalfNum_Solution(numbers) {
let result = null;
const map = new Map();
const halfLen = Math.ceil(numbers.length / 2);
for (const n of numbers) {
if (!map.has(n)) {
map.set(n, 1);
} else {
map.set(n, map.get(n) + 1);
}
}
console.log(map);
map.forEach((value, key) => {
if (value >= halfLen) {
result = key;
}
});
return result;
}
console.log(MoreThanHalfNum_Solution([1, 2, 3, 2, 2, 2, 5, 4, 2]));
console.log(MoreThanHalfNum_Solution([3, 3, 3, 3, 2, 2, 2]));
FindNumsAppearOnce
function FindNumsAppearOnce(array) {
const map = new Map();
const result = [];
for (const num of array) {
if (!map.has(num)) {
map.set(num, 1);
} else {
map.set(num, map.get(num) + 1);
}
}
map.forEach((value, key) => {
if (value === 1) {
result.push(key);
}
});
return result.sort();
}
console.log(FindNumsAppearOnce([1, 4, 1, 6]));
minNumberDisappeared
function minNumberDisappeared(nums) {
const required = [];
nums.forEach((_, i) => required.push(i + 1));
const set = new Set(required);
for (const num of nums) {
if (set.has(num)) {
set.delete(num);
}
}
if (Array.from(set).length) {
return Array.from(set)[0];
} else {
return nums.length + 1;
}
}