#1365有多少少于当前数字的数字

题目:给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目
解法一-查找表之哈希表(另一个查找表是平衡二叉搜索树)
思路:先对数组进行排序,再把排序好的数组存进map,以值为key,以下标为value。那么map中每个key对应的value,即每个值对应的下标就是小于当前元素的个数
代码:
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
int i=0;
int[] sortedArray = Arrays.copyOfRange(nums,0,nums.length);
Arrays.sort(sortedArray);
for(i=0;i<nums.length;i++){ //值作为key,下标作为value
if(!map.containsKey(sortedArray[i])){
map.put(sortedArray[i],i);
}
}
for(i=0;i<nums.length;i++){
sortedArray[i] = map.get(nums[i]);
}
return sortedArray;
}
}
注意点:Integer而不是Integrate;Arrays类的方法;sort的具体实现,元素个数小于47用插入,47~286用快排,若>=286且数组有结构,使用归并;不能int[] sortedArray = nums 否则sortedArray和nums指向同一个地方

解法二
思路:数组中每个元素的值域是0~100,可使用cnt数组记录每个元素出现的次数,那么小于nums[i]的个数就为cnt0+..+cnt[i-1]
代码:class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] cnt = new int[101];
int[] cnt2 = new int[nums.length];
for(int i=0;i<nums.length;i++){
cnt[nums[i]]++;
}
for(int i=1;i<=100;i++){
cnt[i]=cnt[i]+cnt[i-1]; //求和,从0的个数一直加到i的个数,故小于nums[I]的个数应该为cnt[nums[I]-1]
}
for(int i=0;i<nums.length;i++){
cnt2[i] = (nums[i]==0?0:cnt[nums[i]-1]);
}
return cnt2;
}
}

posted @ 2020-10-27 18:33  for_ward  阅读(75)  评论(0)    收藏  举报