diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index e464f716..a3d724fa 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -16,7 +16,7 @@ 换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。 以数组形式返回答案。 - + 示例 1: 输入:nums = [8,1,2,2,3] @@ -35,7 +35,7 @@ 示例 3: 输入:nums = [7,7,7,7] 输出:[0,0,0,0] - + 提示: * 2 <= nums.length <= 500 * 0 <= nums[i] <= 100 @@ -120,8 +120,51 @@ public: ## Java ```java +/** +* 解法一:暴力 +* 时间复杂度:O(n^2) +* 空间复杂度:O(n) +*/ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j < nums.length; j++) { + if (nums[j] < nums[i] && j != i) { // 注意 j 不能和 i 重合 + res[i]++; + } + } + } + return res; + } +} ``` +```java +/** +* 优化:排序 + 哈希表 +* 时间复杂度:O(nlogn) +* 空间复杂度:O(n) +*/ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] res = Arrays.copyOf(nums, nums.length); + Arrays.sort(res); // 是对 res 排序,nums 中顺序还要保持 + int[] hash = new int[101]; // 使用哈希表,记录比当前元素小的元素个数 + for (int i = res.length - 1; i >= 0; i--) { // 注意:从后向前 + hash[res[i]] = i; // 排序后,当前下标即表示比当前元素小的元素个数 + } + // 此时 hash中保存的每一个元素数值 便是 小于这个数值的个数 + for (int i = 0; i < res.length; i++) { + res[i] = hash[nums[i]]; + } + return res; + } +} +``` + + + ## Python ```python @@ -143,4 +186,3 @@ public: * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)