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();
    }
}
如果喜欢本文,给个好评呗!
[参与人数: 0 平均分: 0/5]

订阅可以第一时间收到文章更新通知哟~

发表评论

电子邮件地址不会被公开。