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).
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] 반환 완료!