爱程序网

[LeetCode] Single Number III ( a New Questions Added today)

来源: 阅读:

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?

     

     这是今天刚加上去的一道题。

     个人觉得这道题和之前single number的两道差不多。依旧用hashset即可做出。

     唯一要注意的就是最后return的时候不能直接return hashset。为了偷懒我直接弄了个新的int[]。

     代码如下。~

public class Solution {
    public 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;
        
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助