Cattle off-line programming thematic network "to prove safety offer- 40 interview questions" once an array of numbers that appear only

My personal micro-channel public number: Microstrong

Micro-channel public number ID: MicrostrongAI

Micro-channel public number Description: Microstrong (Bauer) students mainly study machine learning, deep learning, computer vision, intelligent dialogue system-related content, share study notes in the learning process! Look forward to your attention, welcome the exchange of learning progress together!

Know almost home page: https: //www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

Personal blog: https: //blog.csdn.net/program_developer

 Topic links:

https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

Subject description:

 Problem-solving ideas:

(1) spatial complexity for time complexity

Space complexity O (n)and time complexity O (n).

AC has code:

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        num_dic = {}
        result_list = []
        for item in array:
            if item in num_dic.keys():
                num_dic[item] = num_dic[item] + 1
            else:
                num_dic[item] = 1

        for item, count in num_dic.items():
            if count == 1:
                result_list.append(item)

        return result_list


if __name__ == "__main__":
    input_array = [2, 4, 3, 6, 3, 2, 5, 5]
    sol = Solution()
    print(sol.FindNumsAppearOnce(input_array))

(2) using the Python list.count () function, the time complexity iso (n)

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        result_list = []
        for item in array:
            count = array.count(item)
            if count == 1:
                result_list.append(item)

        return result_list

(3) using XOR thought, time complexity O (n), space complexityO (1)

XOR concept: If a, b two values are different, the result is an exclusive OR. If a, b values are the same, the exclusive OR result is 0.

        This is a more difficult problem, very few people can do not need to be prompted once thought the best solution at the time of the interview. Generally when the candidates have not thought of the idea after a few minutes, the interviewer will give some tips. The interviewer could have said: You can consider this array has only one number appears only once, others have emerged twice, how to find this number?

        Both topics are emphasizing a (or two> numbers appear only once, others appear twice what is it that we think of a nature XOR operation:? Any of a number of its own exclusive or are equal to zero. that is, if we turn from start to finish XOR array each number, then the end result is exactly the number appears only once, because those numbers come in pairs of two in all different or offset.

        After want to understand how to solve this simple problem, we go back to the original question, see if you can apply the same ideas. We tried the original array is divided into two sub-arrays so that each sub-array contains a number appears only once, while other figures appear twice in pairs. If this can be split into two arrays, respectively, we can find two numbers only appear once in accordance with the previous approach.

         XOR result of a number of us from start to finish or turn XOR array each number, so the final result is obtained only two appear. Because the other figures have emerged twice, all in exclusive or offset. Because of these two figures is certainly not the same, then the XOR result is certainly not zero, which means that the resulting number of binary representation there is at least one to one. We find the first bit position 1 in the resulting number, referred to as the n-th position. Now we are not the n-th bit is a 1 is a standard digital original array is divided into two sub-arrays, the first sub-array of n bits each number is 1, the second sub-array of each digit n bits are 0. Because our standards are grouped in a digital bit is a 1 or a 0, then the emergence of digital two certainly are assigned to the same sub-array. Because the same number in any one of the two are the same, we can not put two identical numbers assigned to two sub-arrays to go, so we have the original array is divided into two sub-arrays, each sub-array contains a numbers appear only once, while other figures have emerged twice. We already know how to find the only one in an array of numbers appear only once, so far all the problems have been resolved.

        For example, assuming that the input array {2, 4, 3, 6, 3, 2, 5, 5}. When we turn to each number in the array XOR operation, and the result is expressed in binary is 0010. XOR result obtained in the penultimate bit is 1, so we are not the second array 1 is divided into two in accordance with the inverse of a number. The first sub-array {2, 3, 6, 3, 2} in the second to last all numbers are 1, and the second sub-array {4, 5, 5} in the second-lowest of all the numbers are 0. Then as long as these two sub-arrays are divergent or, you can find the first child only appears once in the array of numbers is 6, and the second sub-array occurs only once number is 4.

        I think clearly after the whole process is not difficult to write the code. Here is the code has AC:

# -*- coding:utf-8 -*-
class Solution:

    def FindNumsAppearOnce(self, array):
        # write code here
        if array == None or len(array) < 2:
            return []

        # 对数据进行异或运算
        resultExclusiveOR = 0
        for i in array:
            resultExclusiveOR ^= i

        # 在异或结果中找出从右向左第一个为1的索引
        indexOf1 = self.FindFirstBitIs1(resultExclusiveOR)

        num1 = 0
        num2 = 0
        for j in array:
            if self.IsBit1(j, indexOf1):
                num1 ^= j
            else:
                num2 ^= j

        return [num1, num2]

    def FindFirstBitIs1(self, num):
        indexBit = 0
        while num & 1 == 0:
            num = num >> 1
            indexBit += 1
        return indexBit

    def IsBit1(self, num, indexBit):
        num = num >> indexBit
        return (num & 1)


if __name__ == "__main__":
    input_array = [2, 4, 3, 6, 3, 2, 5, 5]
    sol = Solution()
    print(sol.FindNumsAppearOnce(input_array))

Reference:

[1] wins the Offer, the Haitao.

[2] to prove safety offer- array appears only once in the digital version -Java address: https://www.bilibili.com/video/av88622216?from=search&seid=17735582839041767037     

Published 289 original articles · won praise 1000 · Views 1.2 million +

Guess you like

Origin blog.csdn.net/program_developer/article/details/104575579