Python – 检查给定的列表是否形成连续的不同子数组
给定一个由 A1、A2、A3…….An 形式的元素组成的数组。任务是找出数组是否可以形成为连续的不同子数组。您需要确定数组是否可以转换为由相似元素组成的连续子数组,并且每个元素都有不同的数量。
一旦遇到的元素不应出现在数组的后面,因为它不会是连续的
例子:
Input:[ 1 1 3 6 6 6 ]
Output: YES
Explanation:
The given elements of the can be converted to Contiguous Distinct Set Array in the form of [1, 1] [3] [6, 6, 6]and also
no. of 1’s = 2
no. of 3’s = 1
no. of 6’s = 3
which are distinct
Input:[ 1 1 3 5 2 2 2 3 ]
Output: NO
Explanation:
The given elements of the cannot be converted to Contiguous Distinct Set Array as sub array [3 5 2 2 2 3]
violates the condition(elements need to be contiguous) 3 again appears after 5 and 2.
Input:[9 9 4 4 4 1 6 6]
Output: NO
Explanation:
The given elements of the cannot be converted to Contiguous Distinct Set Array
It is of the form [9, 9] [4, 4, 4] [1] [6, 6] So the elements are present contiguous
But the no. of 9’s=2 which is also equal to the no. of 6’s=2
Hence the no.s of different elements of the array are not Distinct
hence the Answer is NO
解决方案:
Python3
from collections import Counter
# function to check contiguous
# distinct set array
def contig_distinct_setarr(l, n):
c = Counter(l)
a = list(set(l))
b =[]
flag = True
for j in c.values():
# iterating and moving it to another
# array if already present we print NO
# when it finds no. of different elements
# to be equal if no. of x's = no. of y's
# So we break of the loop
if j not in b:
b.append(j)
else:
print("NO")
flag = False
break
# If already there are similar elements
# in c.values()- the count of elements
# flag = False and we dont need to check
# the below condition If not flag = False
# then the iterate through the array loop
if (flag != False):
i, k = 0, 0
# for each elements in set a
# cou stores the count of a[i]
while k
输出:
YES