LeetCode Elementary Algorithm-Numbers that only appear once

Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once.

Explanation:
Your algorithm should have linear time complexity. Can you do it without using extra space?

输入: [2,2,1]
输出: 1

Idea : If you want to achieve linear time complexity of O(n), brute force cracking will definitely not work, you can use the hash method to do it, and you can achieve O(n) complexity.

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer i : nums) {
    
    
            Integer count = map.get(i);
            count = count == null ? 1 : ++count;
            map.put(i, count);
        }
        for (Integer i : map.keySet()) {
    
    
            Integer count = map.get(i);
            if (count == 1) {
    
    
                return i;
            }
        }
        return -1;
    }
}

If you do not use extra space to achieve: using bit operation, a^b ^a = b, because in addition to one number, the rest are 2 times.

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

Guess you like

Origin blog.csdn.net/qq_43360777/article/details/107570919