[leetcode] 5
Leet Code 1365. How Many Numbers Are Smaller Than the Current Number
Problem
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.
Example
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).
해석
입력된 nums Array에서 nums[i]보다 작은 숫자가 nums Array에 몇개가 있는지를 저장해서 result Array에 저장하여 보여주자.자기자신과는 비교하지않고 자신보다 작은 인자가 몇개인지만을 기록하는 result Array를 리턴해주자.
Solution in JavaScript
var smallerNumbersThanCurrent = function(nums) {
var result =[];
for(var i=0;i<nums.length;i++){ 0~nums.length까지 실행할것이다. nums[i]의 가져와서
var count=0;
for(var j=0;j<nums.length;j++){ 자기자신과의 비교는 하지않고 넘어간다.
if(i==j){
continue;
}
else if(nums[i]>nums[j]){ nums[i]가 nums[k]보다 작으면 count를 올린다.
count++;
}
}
result.push(count); nums[i]가 nums[0]~nums[j]까지 다 비교해서 얻은 count값을 result에 저장한다.
}
return result; nums[0]~nums[i]까지 다 확인해후에 count들을 저장한 result array를 리턴한다.
};
Solution in Java
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] result=new int[nums.length]; count 결과를 담을 result array 생성
for(int i=0;i<nums.length;i++){
int count=0; 비교를 다할때 마다 count 초기화
for(int k=0;k<nums.length;k++){
if(k==i)continue; 자기자신은 비교하지 않고 넘어간다. continue
if(nums[i]>nums[k]){
count+=1; 자기자신보다 작은애가 있다면 count를 올린다.
}
}
result[i]=count; 비교를 다한후의 count를 result[i]에 저장한다.
}
return result; count를 다 저장한 result를 비교한다.
}
}