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?

Solution1:持续累积异或

思路:结果就是that single one,appear twice 的会异或成0
Time Complexity: O(N) Space Complexity: O(1)

Solution2:hashset

Time Complexity: O(N) Space Complexity: O(N)

Solution1 Code:

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int i = 0; i < nums.length; i++)
            result ^= nums[i];
        return ans;
    }
}

Solution2 Code:

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

你可能感兴趣的:(136. Single Number)