给定数组A,大小为26*26.判断数组的每一行和每一列由{a,b,c...z}这26个字符组成,这些字符只出现一次。
Given an array A of size 26*26. Determine whether each row and column of the array consists of set {a,b,c,d,.....z} where each element occurs exactly once
由于每个元素至少要访问一次,所以不能将时间复杂度减到O(n2) 以下。
而使用hash每行和每列将会花费空间复杂度为O(n).
换种方式,给每一个字符从a到z一个唯一的素数。
将这26个素数相乘等到乘积m,
从数组的每行和每列中找出相应的26个字符的乘积,
如果每行和每列的乘积和m匹配
返回true
否则返回false...
最后不要认为会减少时间复杂度,每个元素最少要遍历一次。
you cant reduce the time complexity further than O(n2) becoz... u have to visit each element at least once , ofcourse, so, tc > O(n2).
further dont use hashing to check for rach rows and columns as it will take space complexity of O(n).
instead,assign each character from a to z a unique prime number.
find the multiplication of these 26 prime numbers, say m
now find the multiplication of 26 characters present in each rows and columns
if each rows and each columns multiplication match to m.
so return true
else return false..
furthermore, dont think abt to reduce time complexity further.. u cant
u have to go through each element at least for once