LeetCode. How many numbers are less than the current number (Java)

Give you an array nums, for each element nums[i], please count the number of all numbers smaller than it in the array.
In other words, for each nums[i] you must calculate the number of valid j, where j satisfies j != i and nums[j] <nums[i].
The answer is returned as an array.

public int[] smallerNumbersThanCurrent(int[] nums) {
    
    
	if (nums.length == 0 || nums.length == 1) {
    
    
		return nums;
	}
	int[] arr = new int[nums.length];
	for (int i = 0; i < nums.length; i++) {
    
    
		int count = 0;
		for (int j = 0; j < nums.length; j++) {
    
    
			if (i == j) {
    
    
				continue;
			} else if (nums[j] < nums[i]) {
    
    
				count++;
			}
		}
		arr[i] = count;
	}
	return arr;
}

Improvement: In some special cases, see if the following code has been resolved. If you solve it, you don't need to write it again, if not, you still have to write it.

public int[] smallerNumbersThanCurrent2(int[] nums) {
    
    
	int[] arr = new int[nums.length];
	for (int i = 0; i < nums.length; i++) {
    
    
		for (int j = 0; j < nums.length; j++) {
    
    
			if (i == j) {
    
    
				continue;
			} else if (nums[j] < nums[i]) {
    
    
				arr[i]++;
			}
		}
	}
	return arr;
}

end.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/108592325