LeetCode 136: appears only once in the digital Single Number

topic:

Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Description:

Your algorithm should have linear time complexity. You can not use the extra space to achieve it?

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

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

Example 2:

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

Problem-solving ideas:

  • The array is sorted, if a number of the two numbers are not equal before and after the number appears only once.
  • Hash map, key value for each of the number, value of the frequency of occurrence of each number. Finally, find value = number 1 is returned.
  • XOR XOR operation directly evaluated. No additional space.

Exclusive OR operation (XOR) problem-solving is the most elegant solution, without the use of additional space, the concept is:

  • If we do XOR operation on bits 0 and, still get this bit
    • a XOR 0 = a
  • If we do XOR operation on the same binary bits, the result returned is zero
    • a XOR a = 0
  • XOR commutative and associative

Code:

With the hash table:

Java:

Frequency hash map (may be used to calculate the occurrence frequency of the string)

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            Integer count = map.get(num); //get() 方法获取元素不存在时返回null
            count = count == null ? 1 : ++count; //count为null 时证明元素不存在,则频率改为1,否则count频率+1
            map.put(num, count); //加入映射表
        }
        for (Integer num : map.keySet())
            if (map.get(num) == 1) return num; //返回频率为1的数
        return 0;
    }
}

Python:

1, with the try ... except ..., only applies to the problem of repetitive elements repeated number is an even number.

class Solution(object):
    def singleNumber(self, nums):
        hash_map = {}
        for i in nums:
            try:
                hash_map.pop(i) # 尝试移除该数
            except:
                hash_map[i] = 1 # 移除失败证明字典内没有该值,则添加到字典
        return hash_map.popitem()[0] #最后字典中只剩下一个键值对,返回其键值

2, the frequency mapping dictionary (used to calculate the frequency of occurrence of the string)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        hash_map = {}
        for num in nums:
            hash_map.setdefault(num, 0)
            hash_map[num] += 1 # 每次出现频率加一
        for k, v in hash_map.items(): #二次遍历返回频率为1的数
            if v == 1:
                return k
        return 0

Yihuo operation (XOR):

Processing logic which can be simply understood as:

输入: [2 , 3 , 2 , 4 , 3] ,  初始化 result = 0

result = 0  XOR  2  =  2
result = 2  XOR  3  =  [2 , 3]
result =  [2 , 3]  XOR  2  =  3
result = 3  XOR  4  =  [3 , 4]
result = [3 , 4]  XOR  3  =  4

返回 result = 4

Exclusive OR operation is one of the basic arithmetic operations bit, for ease of understanding the above exclusive-OR operation is simplified abstract logical, if want to learn more bit operation, see Encyclopedia Wiki.

High-level programming language symbol represents the XOR operation generally ^.

Java:

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int num : nums)
            result = result ^ num;
        return result;
    }
}

Python:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        result = 0
        for num in nums:
            result = result ^ num
        return result

Micro welcome attention. Letter public. Bug love to write all the numbers
_Bug

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/11655409.html