leetcode954. 二倍数对数组(treemap)
生活随笔
收集整理的這篇文章主要介紹了
leetcode954. 二倍数对数组(treemap)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個長度為偶數(shù)的整數(shù)數(shù)組 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);//減掉已經(jīng)匹配的數(shù)map.put(2*c,map.get(2*c)-t);res+=t;//記錄匹配到的對數(shù)if(res>=n/2) return true;}}return false;} }總結(jié)
以上是生活随笔為你收集整理的leetcode954. 二倍数对数组(treemap)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到新坟是什么意思
- 下一篇: leetcode面试题 17.15. 最