当前位置:网站首页>【LeetCode】954. 二倍数对数组
【LeetCode】954. 二倍数对数组
2022-07-13 18:03:00 【pass night】
题目
给定一个长度为偶数的整数数组 arr,只有对 arr 进行重组后可以满足 “对于每个 0 <= i < len(arr) / 2,都有 arr[2 * i + 1] = 2 * arr[2 * i]” 时,返回 true;否则,返回 false。
示例 1:
输入:arr = [3,1,3,6]
输出:false
示例 2:
输入:arr = [2,1,2,6]
输出:false
示例 3:
输入:arr = [4,-2,2,-4]
输出:true
解释:可以用 [-2,-4] 和 [2,4] 这两组组成 [-2,-4,2,4] 或是 [2,4,-2,-4]
提示:
0 <= arr.length <= 3 * 104arr.length是偶数-105 <= arr[i] <= 105
思路
- 将数组升序排列,左侧的数只可能匹配其右侧的数,所以升序排列后可以从左到右遍历数组
- 因为0可以匹配它自身,所以单独考虑,匹配数为 ⌊ n u m b e r o f z e r o ÷ 2 ⌋ \lfloor number\ of \ zero \div2\rfloor ⌊number of zero÷2⌋
代码
from collections import Counter
class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
arrCounter = Counter(arr)
count = 0
arr.sort()
# zero can be paired to itself
count += arrCounter[0] // 2
arrCounter[0] = 0
for n in arr:
if count == len(arr)//2: return True
if arrCounter[2*n] > 0 and arrCounter[n] > 0:
arrCounter[2*n] -= 1
arrCounter[n] -= 1
count += 1
return count == len(arr)//2
复杂度
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
边栏推荐
- Basic knowledge of redis - rookie tutorial
- 【LeetCode】380. O(1) 时间插入、删除和获取随机元素
- SAP ABAP BAPI_MATERIAL_AVAILABILITY 查询可用库存
- 通俗讲Cookie,Session,Token区别
- SAP BW extraction layer error s:aa 821 (bukrs)
- Hardware course design: system design of multi-function player based on stm32
- One way linked list implements queue and stack
- 863. All Nodes Distance K in Binary Tree
- Men should be "strong", not "soft", "weak" and "empty"
- 浅谈框架中xml文件格式的含义
猜你喜欢

SAP DUMP CALLBACK_REJECTED_BY_WHITELIST - SE51, RSSCREENPAINTER

Shut up that thing

Volatile最终解释

2021/12/12攻防世界reverse做题记录

SAP DUMP CALLBACK_ REJECTED_ BY_ WHITELIST - SE51, RSSCREENPAINTER

数据存储与容灾(第2版)主编 鲁先志 武春岭综合训练答案

ScheduledThreadPoolExecutor源码和误区详解

MySQL - data page

2021/12/12 攻防世界 crypto做题记录

Basic knowledge of redis - rookie tutorial
随机推荐
2、 Implementation of software RAID experiment report
MySQL error messages errors
线程机制与事件机制
Implementation of list class template of bidirectional linked list
128. Longest continuous sequence
863. All Nodes Distance K in Binary Tree
SAP ABAP BAPI_ACC_DOCUMENT_POST 创建会计凭证
Chrome realizes automated testing: recording and playback web page actions
Leetcode lecture - 1217 Play chips (difficulty: simple)
SAP DUMP CX_ SY_ CONVERSION_ NO_ NUMBER
二、實現軟件RAID實驗報告
Implementation of [priority queue (heap)] binary heap class template
【LeetCode】442. 数组中重复的数据
题:二叉树的最近公共祖先
组合模式应用
Implementation of binarysearchtree (BST) class template for binary search tree
Common commands for IPDB debugging
Title: the nearest common ancestor of binary tree
【6月4号学习进度】
【LeetCode】380. O(1) 时间插入、删除和获取随机元素