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

找单数

时间:2015-08-30 23:06:16      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:

一个int数组中的元素有这样的特点:两两出现,只有2个数字是单独的。

找到这2个数字,返回一个int数组。

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

用Java实现,核心方法如下:

    public static int[] singleNumber(int[] nums) {
        if(nums.length==2&&nums[0]!=nums[1]){
            return nums;
        }
   
        HashSet<Integer> store=new HashSet<Integer>();
        HashSet<Integer> result=new HashSet<Integer>();
        for(int i=0;i<nums.length;i++){
            if(!result.add(nums[i])){
                result.remove(nums[i]);
                store.add(nums[i]);
            }else{
                if(store.contains(nums[i])){
                    result.remove(nums[i]);
                }
            }
        }
        int[] print=new int[2];
        print[0]=result.iterator().next();
        result.remove(result.iterator().next());
        print[1]=result.iterator().next();
        return print;
         
    }

使用的是HashSet来存储数据

HashSet的add方法返回一个boolean值。第一次添加数据时返回true,再添加同样的数据时返回false

        HashSet<Integer> test = new HashSet<Integer>();
        System.out.print(test.add(1) + "\t");
        System.out.print(test.add(1));
        System.out.print("\n" + test.add(2) + "\t");
        System.out.println(test.add(3));
        for (int i = 1;i <= 3; i++){
            System.out.print("item" + i + ":" + test.iterator().next() + "\t");
            test.remove(test.iterator().next());    //删去当前值
        }

其中数据“1”执行了2次添加操作;打印出

true false
true true
item1:1 item2:2 item3:3

可以看出添加2次,实际只有1个

利用add方法返回的Boolean值,能判断是否已经把数据添加进map中

 

找单数

标签:

原文地址:http://www.cnblogs.com/rustfisher/p/4771839.html

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