首页 > 其他 > 详细

find unique values in an array

时间:2014-11-15 06:34:49      阅读:293      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/miaoz/p/4098647.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!