給定一個長度為偶數的整數數組 A,只有對 A 進行重組后可以滿足 “對于每個 0 <= i < len(A) / 2,都有 A[2 * i + 1] = 2 * A[2 * i]” 時,返回 true;否則,返回 false。
示例 1:
輸入:[3,1,3,6]
輸出:false
代碼
class Solution {public boolean canReorderDoubled(int[] A) {int n=A.length,res=0;if(n==0) return true;TreeMap<Integer,Integer> map=new TreeMap<>();for(int c:A) map.put(c,map.getOrDefault(c,0)+1);//初始化for(int c:map.keySet()){if(map.containsKey(2*c)&&map.get(c)>0&&map.get(c*2)>0) {int t;if(c==0)//特殊情況t=map.get(0)/2;else t= Math.min(map.get(c),map.get(2*c));map.put(c,map.get(c)-t);//減掉已經匹配的數map.put(2*c,map.get(2*c)-t);res+=t;//記錄匹配到的對數if(res>=n/2) return true;}}return false;}
}