[LeetCode] Most Frequent Number Following Key In an Array

준규·2023년 3월 30일
0

1.문제


You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.

For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that:

  • 0 <= i <= nums.length - 2,
  • nums[i] == key and,
  • nums[i + 1] == target.

Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.


index가 0부터 시작하는 정수배열이 주어지고 key가 주어진다.

nums에서 key값 바로 다음에 나오는 target값이 가장 많이 나타나는 target값을 리턴하면 되는 문제이다.


Example 1

Input: nums = [1,100,200,1,100], key = 1
Output: 100
Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.
No other integers follow an occurrence of key, so we return 100.

Example 2

Input: nums = [2,2,2,2,3], key = 2
Output: 2
Explanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.
For target = 3, there is only one occurrence at index 4 which follows an occurrence of key.
target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.

Constraints:

  • 2 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • The test cases will be generated such that the answer is unique.

2.풀이

  1. for문을 돌면서 key값을 찾는다.
  2. key 값을 찾으면 다음 값의 등장 횟수를 객체에 저장한다.
  3. 객체를 순회하면서 value 값이 가장 큰 key값을 찾는다.
  4. 해당 key 값의 value를 리턴한다.

/**
 * @param {number[]} nums
 * @param {number} key
 * @return {number}
 */
const mostFrequent = function (nums, key) {
  let map = {};
  let maximum = -Infinity;

  // for문을 돌면서 key값 바로 뒤의 target의 개수를 세서 객체에 저장한다.
  for (let i = 0; i < nums.length - 1; i++) {
    if (nums[i] === key) {
      if (!map[nums[i + 1]]) {
        map[nums[i + 1]] = 1;
      } else {
        map[nums[i + 1]]++;
      }
    }
  }

  const keys = Object.keys(map);

  // 객체 내에서 value 값이 가장 큰 key값을 구한다
  for (let i = 0; i < keys.length; i++) {
    if (maximum <= map[keys[i]]) {
      maximum = map[keys[i]];
    }
  }

  // 구한 key값의 value 값을 리턴한다.
  return keys.find((key) => map[key] === maximum);
};

3.결과

profile
안녕하세요 :)

0개의 댓글