hash problems

steyu·2022년 10월 27일
0

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])); // 2
console.log(MoreThanHalfNum_Solution([3, 3, 3, 3, 2, 2, 2])); //3

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])); // [4,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;
  }
}

// console.log(minNumberDisappeared([1, 0, 2])); //3
// console.log(minNumberDisappeared([-2, 3, 4, 1, 5])); //2
// console.log(minNumberDisappeared([4, 5, 6, 8, 9])); //1
// console.log(minNumberDisappeared([3, 2, 1])); //4

0개의 댓글