136. Single Number

来源:互联网 发布:中国运营商网络制式 编辑:程序博客网 时间:2024/06/05 10:07

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?

直接的想法是两层循环找到那个异常的数据,但是时间复杂度较高。由于异或可以在消除两个相同的数且具有交换性,所以想到了使用异或相加的方法如下:

class Solution {    public int singleNumber(int[] nums) {        if (nums == null || nums.length == 0) {            return Integer.MIN_VALUE;        }        int res = nums[0];        for (int i = 1; i < nums.length; i++) {            res ^= nums[i];        }        return res;    }}

使用HashSet,在插入的时候如果已在set中就把set里对应的元素删除,否则就插入,最后剩下的就是那个只有一个元素的值。

class Solution {    public int singleNumber(int[] nums) {        if (nums == null || nums.length == 0) {            return Integer.MIN_VALUE;        }        HashSet hs = new HashSet();        for (int i=0;i<nums.length;i++){            if (hs.contains(nums[i])) hs.remove(nums[i]);            else hs.add(nums[i]);        }        Iterator<Integer> it = hs.iterator();        return it.next();    }}