排序+哈希表。
将数组排序之后,枚举所有元素,如果元素c的平方根v已经存在,则在哈希表中存入c,令map[c]=map[v]+1;否则直接在哈希表中令map[c]=1。最后哈希表中的最大值即可。
class Solution {
public:
int longestSquareStreak(vector<int>& a) {
sort(a.begin(),a.end());
unordered_map<int,int> mp;
for(auto c:a){
int v=sqrt(c);
if(v*v==c&&mp.count(v)) mp[c]=mp[v]+1;
else mp[c]=1;
}
int ans=-1;
for(auto c:mp) if(c.second>1) ans=max(ans,c.second);
return ans;
}
};
时间复杂度:O(nlogn),n为数组长度。
空间复杂度:O(n)。