题目是周赛的第二题,难度中等。
题目描述:
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
其他说明:
0 <= A.length <= 30000
A.length is even
-100000 <= A[i] <= 100000
题目分析:
这道题是数组内满足某条件的元素是否存在的问题。
这道题是来判断是否数组内的全部元素都可以组成(x,2x)这样的元组。
如 [16,8,32,4]就可以组成(4,8)、(16,32)。
思路
对数组各个元素出现的个数计数,x为某元素值,counter[x]是该元素出现次数。
按照元素绝对值从小到大排序,判断counter[2*x]是否大于counter[x],如果counter[2*x] > =counter[x], 可以确定形成 counter[x] 个(x,2*x)个对。
因为按照绝对值从小到大排序后,当遍历到某元素A[i]时,数组中A[i]/2要么不存在,要么已经和A[i]/4成对,也就是说不能再使用了。对于A[i], 当且仅当数组中存在A[i]*2条件才可以满足,考虑到有重复元素的情况,counter[A[i]] <= counter[A[i]*2].
数据结构
根据场景选择数据结构:
python: collections.counter() python中的计数器
返回dict类型:key为元素值,value为元素出现的个数。
c++、java:Map储存元素及计数结果
python实现:
class Solution:
def canReorderDoubled(self, A):
c = collecitons.counter(A)
for i in sorted(c,key=lamda x : abs(x)):
if c[i] > c[2*i]:
return False
else:
c[2*i]-=c[i]
其中sorted 函数内部是Timsort排序算法,结合了合并排序(merge sort)和插入排序(insertion sort)。最坏情况下时间复杂度为O(nlogn),当待排序的数组中已经有排序好的数,它的时间复杂度会小于n logn。