关于解决Missing Number之类的算法问题

停止刷题已经三周了,有些想念。最近总算完成了公司代码的重构,于是要继续开始学习算法。

先来看leetcode上面第268题:

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

这个题写的是给你一个排序好的数组,然后你需要找到这个数组里面缺的那个数字,而且需要使用线性复杂度O(n)和constant extra space常数级别的空间O(1)。

这类题要做成O(n)的时间复杂度其实都是一个思路,就是使用异或进行两两抵消。异或及是一种对位相加不进位的操作,比如5 和 3 进行异或就是 0101 和0011是 0110就是6。相同的按位与为0 不同的按位与为1。

这道题只需要制造一个n长度的队列,然后依次与given_nums 与,最后剩下的数就是缺少的数:

xor = 0
i = 0
pipi = [0, 1, 3, 4]

for i in range(len(pipi)):
    xor = xor ^ i ^ pipi[i]
i += 1
print xor ^ i

就可以得到结果2。

类似的思路其实还可以解不少题。例如给你一堆成对的数 只落单了一个数让你找出他。

例如给你一个p = [5, 4, 3, 2, 2, 3, 5] 少了一个4 让你把他用O(n)的复杂度 把他找出来就非常适用于这种方法。

两两按位与之后就会得到4. 所以可以总结出一个公式 0 = X XOR X

以上。

原文地址:https://www.cnblogs.com/piperck/p/6220987.html