LeetCode:136, Single Number(找出单个数字)

Given a non-empty 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?

Example 1:


Input: [2,2,1]
Output: 1

Example 2:


Input: [4,1,2,1,2]
Output: 4

解题方法1:

private int getSingleNumer2(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int ele : nums) {
            if (set.contains(ele)) {
                set.remove(ele);
            } else {
                set.add(ele);
            }
        }
        return (int)set.toArray()[0];
    }

利用set集合进行处理;

时间复杂度:O(n);

空间复杂度:  O(n);

解题方法2:

 private int getSingleNumer4(int[] nums) {
        int singleNumber = nums[0];
        for (int i=1;i<nums.length;i++) {
             singleNumber ^=nums[i];
        }
        return singleNumber;
    }

利用异或进行处理;

时间复杂度:O(n);

空间复杂度:O(1);

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/83185189