<문제 1365. How Many Numbers Are Smaller Than the Current Number>
[문제]
번역 :
[배열 nums가 주어졌을 때, 각 nums[i]에 대해 배열에서 이보다 작은 숫자가 몇 개 있는지 구합니다.
즉, 각 nums[i]에 대해 j != i, nums[j] < nums[i]가 되도록 유효한 j의 개수를 세어야 합니다.
배열로 답을 반환합니다.]
→ 문제 그대로 nums[i]에 대해 배열에서 i보다 작은 숫자가 몇 개 있는지 구하는 문제
예를 들어, {8,1,2,2,3}이 있다고 했을 때, 맨처음 i = 8, 8보다 작은 숫자는 1, 2, 2, 3이 있으므로 4개가 있다고 볼 수 있다.
[답안]
import java.util.Arrays;
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] answer = new int[nums.length]; // 답은 nums배열과 크기가 같다.
int cnt; // i번째 배열보다 작은 수를 카운트해줄 변수
for (int i = 0; i < nums.length; i++) {
cnt = 0; // 한번 돌 때마다 cnt값 초기화 해주기
for (int j = 0; j < nums.length; j++) {
if (nums[i] > nums[j]) cnt++; // 만약 j값이 i보다 작으면 카운트++
}
answer[i] = cnt; // 카운트 수 answer에 담기
}
return answer; // answer 리턴
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {8, 1, 2, 2, 3};
int[] nums2 = {6, 5, 4, 8};
int[] nums3 = {7, 7, 7, 7};
System.out.println(Arrays.toString(sol.smallerNumbersThanCurrent(nums)));
System.out.println(Arrays.toString(sol.smallerNumbersThanCurrent(nums2)));
System.out.println(Arrays.toString(sol.smallerNumbersThanCurrent(nums3)));
}
}
출처
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/description/
How Many Numbers Are Smaller Than the Current Number - LeetCode
Can you solve this real interview question? How Many Numbers Are Smaller Than the Current Number - 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
leetcode.com