首页 > 代码库 > find unique values in an array
find unique values in an array
Problem:
given an array that contains duplicates (except one value), find the one value that does not have a duplicate in that array. Explain the complexity of your algorithm. So in the array: A = [2, 3, 4, 5, 2, 3, 4] your algorithm should return 5 since that‘s the value that does not have a duplicate.
Solution:
this can be solved using a HashMap (two pass through). Or 2 HashSets (1 pass through).
I will show the 2nd solution (2 hashset)
import java.util.*;public class Dup{ public static void main(String[] args){ int[] n= {2,3,4,5,2,3,4,1,1,1}; Set<Integer> all= new HashSet<>(); Set<Integer> unq= new HashSet<>(); for(int i:n){ if(all.contains(i)){ unq.remove(i); } else{ all.add(i); unq.add(i); } } Iterator i= unq.iterator(); while(i.hasNext()){ System.out.println(""+ i.next()); } }}
find unique values in an array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。