Add Two Numbers With Bit Operation
Question: Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and »
Question: Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and »
这道题目算法上没有什么特别的,更像是一道找规律的数学题目。我们知道,n个数的permutation总共有n阶乘个,基于这个性质我们可以得到某一位对应的数字是哪一个。思路是这样的,比如当前长度是n,我们知道每个相同的起始元素对应(n-1)!个permutation,也就是(n-1)!个permutation后会换一个起始元素。因此,只要当前的k进行(n-1)!取余,得到的数字就是当前剩余数组的index,如此就可以得到对应的元素。如此递推直到数组中没有元素结束。实现中我们要维护一个数组来记录当前的元素,每次得到一个元素加入结果数组,然后从剩余数组中移除,因此空间复杂度是O(n)。时间上总共需要n个回合, »
It takes a while to figure out the solution on O(n^2) with no extra spaces. The idea is that loop the array to make »