题目如下:

Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2.

Example 1:

Input: [3,1,3,6]
Output: false

Example 2:

Input: [2,1,2,6]
Output: false

Example 3:

Input: [4,-2,2,-4]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].

Example 4:

Input: [1,2,4,16,8,4]
Output: false

Note:

  1. 0 <= A.length <= 30000
  2. A.length is even
  3. -100000 <= A[i] <= 100000

解题思路:本题难度不大,思路也非常简单。遍历A,同时用字典dic记录A中每个元素出现的次数,如果A[i] 是偶数并且A[i]/2存在于dic中,那么把A[i]/2在dic中出现的次数减去1,如果出现次数降为0,从dic中删除该key值;否则继续判断A[i]*2是否存在于dic中;如果两个条件都不满足,把A[i]加入dic中。最后判断dic的长度是否为0即可,

代码如下:

class Solution(object):
def canReorderDoubled(self, A):
"""
:type A: List[int]
:rtype: bool
"""
A.sort()
dic = {}
for i in A:
if i % 2 == 0 and i/2 in dic:
i = i / 2
dic[i] -= 1
if dic[i] == 0:
del dic[i]
elif i * 2 in dic:
i = i * 2
dic[i] -= 1
if dic[i] == 0:
del dic[i]
else:
dic[i] = dic.setdefault(i, 0) + 1
continue
return len(dic) == 0

最新文章

  1. js对象3.1--什么是类,对象--杂志
  2. 【原创】MapReduce计数器
  3. 转:CSS选择器笔记
  4. linux开机启动smb服务
  5. apache如何设置缓存
  6. Linux驱动手动绑定和解绑定
  7. selenium设置proxy、headers(phantomjs、Chrome、Firefox)
  8. 论文选读二:Multi-Passage Machine Reading Comprehension with Cross-Passage Answer Verification
  9. HDU 6228 - Tree - [DFS]
  10. Echart绘制趋势图和柱状图总结
  11. 梯度下降法、牛顿法、高斯牛顿法、LM最优化算法
  12. js第三天知识点 循环
  13. 访问前台页面${pageContext.request.contextPath}/el表达式失效问题解决
  14. 解题:POJ 2888 Magic Bracelet
  15. Android——开机启动功能(Service和BroadcastReceiver)
  16. jmeter --自动化badboy脚本开发技术
  17. jQuery和$、jQuery(function(){})和(function(){})(jQuery)
  18. IOS UITableView索引排序功能
  19. 将Log4J的日志内容发送到agent的source
  20. CSS01--概述与选择器

热门文章

  1. tensorflow报错
  2. SQO2008配置管理工具服务显示远程过程调用失败0x800706be
  3. python字符串的截取,查找
  4. PHP FILTER_SANITIZE_STRING 过滤器
  5. [MySQL] innobackupex在线备份及恢复(全量和增量)
  6. 2019 ICPC Asia Nanchang Regional C And and Pair 找规律/位运算/dp
  7. datetime timestamp使用
  8. 微信支付(JsApi)
  9. JSP 虚拟路径设置
  10. HDU 3746 Cyclic Nacklace (KMP找循环节)