Fast checking if array has repeated elements or not

I need to check whether a given array, A has repeated elements or not and return in true or false. The function runs near about 5*10^6 times. Initially I tried this
function flag = hasNoRepeats(A)
flag = numel(A)==numel(unique(A)) ;
end
This is very slow, it takes about 90-100 seconds. It is given that array has all positive integers and they are in between 1 and K.
function flag = hasNoRepeats(A,K)
tmp = zeros(1,K);
flag = true;
for i=1:numel(A)
if tmp(A(i))
flag = false;
break
end
tmp(A(i)) = 1;
end
end
This version is faster (~20 secs) but still slower than my requirements. Is there any way to do it faster?

4 件のコメント

Mehmed Saad
Mehmed Saad 2020 年 4 月 8 日
flag = sum(diff(sort(A)))>1;
Try this and tell me what time it got?
Dhritishmam Sarmah
Dhritishmam Sarmah 2020 年 4 月 8 日
Sorry, your code doesn't work. Try taking a random array, A=randi(20,1,6). But still I tried using sort and got improved time (~12sec).
function flag = hasNoRepeats(A,K)
flag = true;
A = sort(A);
for i=1:(numel(A)-1)
if A(i)==A(i+1)
flag = false;
break;
end
end
end
Alex Mcaulley
Alex Mcaulley 2020 年 4 月 8 日
Using sort and diff you can try with:
flag = ~sum(~diff(sort(A)));
Dhritishmam Sarmah
Dhritishmam Sarmah 2020 年 4 月 8 日
Thanks Alex. But it seems like my implementation using sort gives the best timing yet so I will stick with it for the moment.

サインインしてコメントする。

回答 (1 件)

KSSV
KSSV 2020 年 4 月 8 日
編集済み: KSSV 2020 年 4 月 8 日

0 投票

You can simply use unique to find out whether a array has repeated elements or not.
Let A be your array.
if length(A)==length(unique(A))
fprintf("A has no repeated elements") ;
else
fprintf("A has repeated elements") ;
end

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2020 年 4 月 8 日

編集済み:

2020 年 4 月 8 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by