码迷,mamicode.com
首页 > 其他好文 > 详细

find unique values in an array

时间:2014-11-15 06:35:12      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   java   for   div   

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

标签:style   blog   io   color   ar   sp   java   for   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!