力扣算法:954题
题目描述:
也就是说给你一个数组,如果满足其中一半是另一半的二倍,则结果返回true,否则结果返回false。
示例:
核心算法实现
这里面主要是要求满足的是,数组的一半是另一半的二倍,这里面我们主要设计到hashmap的使用。如果我们对这个数组进行从小到大进行排序的话,则排序后的数组前面的一定是后面的一半,则我们如果要找二倍值的话一定是在后面进行找。
****这里面我们以数组 A[]={-2,-2,-4,-4,1,2,4,8},来进行举例。
- 这里面数组的值可能会出现重复,所以我们需要进行记录一下每个值出现的次数。
我们创建:
Map<Inteager,Inteager> count=new hashmap()<>;
这里面我们根据数组中的值计算每个值出现的次数。创建的过程为:
for(int x:A){
count.put(x,count.getOrDefault(x,0)+1);
}
这里面的getOrDefault(x,0)表示的是如果x存在与map中,则取出map的Value值加1,不存在添加到map中,默认值为0+1;
举例说明:
public static void main(String[] args) {
Map<Integer, Integer> map=new HashMap<>();
map.put(1,2);
map.getOrDefault(1,3);
map.put(2,map.getOrDefault(2,0)+1);
System.out.println(map.get(1));
System.out.print(map.get(2));
}
- 创建一个数组用于保存结果
//2,创建一个保存结果的数组B
Integer[] B=new Integer[A.length];
for(int i=0;i<A.length;i++){
B[i]=A[i];
}
- 然后对数组B进行按照绝对值的顺序来进行排序
Arrays.sort(B, Comparator.comparingInt(Math::abs));
- 开始进行判定,这里面我们依次遍历数组B
for(int x:B){
if(count.get(x)==0) continue;
if(count.getOrDefault(2*x,0)<=0) return false;
count.put(x,count.get(x)-1);
count.put(2*x,count.get(2*x)-1);
}
return true;
我们遍历某一个值比如遍历到-2的时候,首先我们判断-2是不是还存在了,因为有可能-2已经让前面的数给占据了,所以我们首先需要判定当前值是否还存在。
如果不存在跳过当前值判断。
如果存在则判断2*x是否存在,如果不存在倍数则返回错误。
如果存在则将两个数都减一。
最后如果遍历完全返回true。
总结
public boolean canReorderDoubled(int[] A) {
//1,创建hashmap用于存储数组中各个值出现的次数
Map<Integer,Integer> count=new HashMap<>();
for(int x:A){
count.put(x,count.getOrDefault(x,0)+1);
}
//2,创建一个保存结果的数组B
Integer[] B=new Integer[A.length];
for(int i=0;i<A.length;i++){
B[i]=A[i];
}
Arrays.sort(B, Comparator.comparingInt(Math::abs));
for(int x:B){
if(count.get(x)==0) continue;
if(count.getOrDefault(2*x,0)<=0) return false;
count.put(x,count.get(x)-1);
count.put(2*x,count.get(2*x)-1);
}
return true;
}