【leetcode】954. Array of Doubled Pairs
2024-10-07 18:37:01
题目如下:
Given an array of integers
A
with even length, returntrue
if and only if it is possible to reorder it such thatA[2 * i + 1] = 2 * A[2 * i]
for every0 <= i < len(A) / 2
.Example 1:
Input: [3,1,3,6]
Output: falseExample 2:
Input: [2,1,2,6]
Output: falseExample 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: falseNote:
0 <= A.length <= 30000
A.length
is even-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
最新文章
- js对象3.1--什么是类,对象--杂志
- 【原创】MapReduce计数器
- 转:CSS选择器笔记
- linux开机启动smb服务
- apache如何设置缓存
- Linux驱动手动绑定和解绑定
- selenium设置proxy、headers(phantomjs、Chrome、Firefox)
- 论文选读二:Multi-Passage Machine Reading Comprehension with Cross-Passage Answer Verification
- HDU 6228 - Tree - [DFS]
- Echart绘制趋势图和柱状图总结
- 梯度下降法、牛顿法、高斯牛顿法、LM最优化算法
- js第三天知识点 循环
- 访问前台页面${pageContext.request.contextPath}/el表达式失效问题解决
- 解题:POJ 2888 Magic Bracelet
- Android——开机启动功能(Service和BroadcastReceiver)
- jmeter --自动化badboy脚本开发技术
- jQuery和$、jQuery(function(){})和(function(){})(jQuery)
- IOS UITableView索引排序功能
- 将Log4J的日志内容发送到agent的source
- CSS01--概述与选择器
热门文章
- tensorflow报错
- SQO2008配置管理工具服务显示远程过程调用失败0x800706be
- python字符串的截取,查找
- PHP FILTER_SANITIZE_STRING 过滤器
- [MySQL] innobackupex在线备份及恢复(全量和增量)
- 2019 ICPC Asia Nanchang Regional C And and Pair 找规律/位运算/dp
- datetime timestamp使用
- 微信支付(JsApi)
- JSP 虚拟路径设置
- HDU 3746 Cyclic Nacklace (KMP找循环节)