Is there any easy way to check if two arrays contain any common elements?
Is this appropriate? The arrays contain type char.
Arrays.asList(encryptU).contains(Ualpha[randNum]));
thanks in advance!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the arrays are small, then a solution with a nested for loop (e.g. @scaryrawr’s) is going to perform best.
If the arrays are large enough, then the
O(N^2)complexity of the above solution will be problematic. The solution is to use a HashSet; e.g.This is
O(N)in time, though the constant of proportionality is rather large. (I think you’d need the product of the array sizes to be 20 or 30 for this to be faster than the nested loop solution … but that is a guess.) Also, this requiresO(N)temporary space.If the range of the characters is limited, then you could use a
BitSetinstead of aHashSet. That will also be roughlyO(N)in time and space, though the range of the characters is also a factor in the complexity, so calling itO(N)is an over-simplification.But we are probably “over-thinking” this. The best advice would probably be to implement something simple, and if there is a suspicion that performance is a real concern then profile it to avoid wasting your time with unnecessary optimizing.