[LeetCode] Count Elements With Strictly Smaller and Greater Elements

준규·2023년 1월 19일
0

1.문제


Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.


정수 배열이 주어질 때 배열에서 임의의 숫자를 하자 골랐을 때 배열안에 고른 숫자보다 작은 값과 큰 값이 모두 존재하는 임의의 숫자의 개수를 리턴하면 되는 문제이다.


Example 1

Input: nums = [11,7,2,15]
Output: 2
Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it.
In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.

Example 2

Input: nums = [-3,3,3,90]
Output: 2
Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.
Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.

Constraints:

  • 1 <= nums.length <= 100
  • -10^5 <= nums[i] <= 10^5

2.풀이

  1. 배열속 숫자들의 총 개수에서 최대값과 최소값의 개수를 빼주면 된다.
  2. 만약 최대값과 최소값이 동일하다면 조건을 만족하는 숫자는 존재하지 않는다.

/**
 * @param {number[]} nums
 * @return {number}
 */
const countElements = function (nums) {
  //오름차순으로 정렬
  nums.sort((a, b) => a - b);

  // 배열 내 최소값과 최대값을 저장한다
  const min = Math.min(...nums);
  const max = Math.max(...nums);

  // 최소값과 최대값이 동일하면 0 리턴
  if (min === max) return 0;

  let minCount = 0;
  let maxCount = 0;

  // 최소값이 배열안에 몇개있는지 count
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === min) minCount++;

    if (nums[i] > min) break;
  }

  // 최대값이 배열안에 몇개있는지 count
  for (let i = nums.length - 1; i >= 0; i--) {
    if (nums[i] === max) maxCount++;

    if (nums[i] < max) break;
  }

  // 배열 안 숫자의 총 개수에서 최소값의 개수와 최대값의 개수를 빼면 된다.
  return nums.length - minCount - maxCount;
};

3.결과

profile
안녕하세요 :)

0개의 댓글