1365. How Many Numbers Are Smaller Than the Current Number

Jeon seong jin·2020년 4월 7일
0

알고리즘

목록 보기
7/9

문제

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

Return the answer in an array.

예시)
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

  • input으로 받는 각 요소를 비교하여 요소가 클 경우에 하나씩 카운터를 늘려 새로운 배열로 output을 리턴받는 문제!

해결 방안

  • 처음에는 각 배열요소를 순회해야 한다고 생각했고, 빈 배열 안에 값을 push한다라고 생각했다.
    처음 풀고자 했던 코드
const solution = (nums) => {
  let answer = [];
  var count = 0;
  for(let i = 0; i < nums.length; i++ ){ 
    for(let j = i + 1; j < nums.length; j++) {
      if(nums[i] > nums[j]){
        count += 1;
      }
    }
  }
  answer.push(count)
  return answer;
}
solution([6,5,4,8])

이렇게 풀어보니 한개의 요소만 카운트가 올라가고 반환이 되는 문제점이 있었다...
다시 풀어 본 코드

const solution = (nums) => {
  let answer = []; //빈배열 생성
  for(let i = 0; i < nums.length; i++ ){ 
    answer[i] = 0; //빈 배열에[i]"요소"를 카운트를 위해 0으로 값 지정
    for(let j = 0; j < nums.length; j++) {
      if(nums[i] > nums[j]){
        console.log(nums[i])
        answer[i] += 1; //카운트를 늘리기 위함
      }
    }
  }
  return answer;
}
solution([6,5,4,8])
// 결과 값 : [2,1,0,3] 반환 완료!

느낀점

  • 유연한 사고를 하자! 하나의 방법이 될거라 생각한 것이 안된다면 다양한 방법으로 생각을 해야겠다는 걸 느꼈다.
  • 배열의 인자를 유연하게 사용하는 연습이 필요할 거 같다.
profile
-기록일지

0개의 댓글