LeetCode – 136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

这个直接用hashset,放进去,第二次的时候移出。

public class Solution {
    public int singleNumber(int[] nums) {
        HashSet<Integer> check = new HashSet();
        for(int i=0;i<nums.length;i++){
            if(!check.remove(nums[i])){
                check.add(nums[i]);
            }
        }
        return check.iterator().next();
    }
}

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 136. Single Number》

127
0 0 127

延伸阅读

发表回复

登录后才能评论
分享本页
返回顶部