avatar
m*n
1
昨天被问了一道老题. array={a1, a2, ..., an, b1, b2, ..., bn}变成 {a1,bn,a2,
bn-1,...,bn,a0},要求时间复杂度O(N),空间O(1).
当时根本不会,我所知道最快的算法是类似quick sort的方法,要O(NlogN), 这个O(N)怎
么做? 我记得以前有人贴过,找不到了.
还有不用random, time种子什么的, 怎么给shuffle任意一个数组,
大概就是
void shuffle(int A[]){
}
每次出来的 A 的结果不一样.
avatar
C*t
3
There are 2 ways to do these.
|--A1--|---A2---|---B1---B2---|
Evenly divide An and Bn into (A1,A2), (B1,B2) respectively.
len(A2) - len(A1) = len(B2) - len(B1) == 1 or 0 depends on odd or even.
Method 1: O(n*logn)
1a. Exchange A2 and B1.
1B. recursively do this on two new subarrays A1+B1, A2+B2
Method 2 : O(n)
2a. The idea is the same as Method 1. Now for each index from 0 to 2*n-1, we
have 4 different domains A1, A2, B1, B2.
2b. Map index of A1 to even index of 2*len(A1)
Map index of B1 to odd index of 2*len(A1)
Map index of A2 to 2*(n//4) + even index of 2*len(A2)
Map index of B2 to 2*(n//4) + odd index of 2*len(A2)

【在 m*****n 的大作中提到】
: 昨天被问了一道老题. array={a1, a2, ..., an, b1, b2, ..., bn}变成 {a1,bn,a2,
: bn-1,...,bn,a0},要求时间复杂度O(N),空间O(1).
: 当时根本不会,我所知道最快的算法是类似quick sort的方法,要O(NlogN), 这个O(N)怎
: 么做? 我记得以前有人贴过,找不到了.
: 还有不用random, time种子什么的, 怎么给shuffle任意一个数组,
: 大概就是
: void shuffle(int A[]){
: }
: 每次出来的 A 的结果不一样.

avatar
h*k
4
你这空间不是O(1)吧

we

【在 C****t 的大作中提到】
: There are 2 ways to do these.
: |--A1--|---A2---|---B1---B2---|
: Evenly divide An and Bn into (A1,A2), (B1,B2) respectively.
: len(A2) - len(A1) = len(B2) - len(B1) == 1 or 0 depends on odd or even.
: Method 1: O(n*logn)
: 1a. Exchange A2 and B1.
: 1B. recursively do this on two new subarrays A1+B1, A2+B2
: Method 2 : O(n)
: 2a. The idea is the same as Method 1. Now for each index from 0 to 2*n-1, we
: have 4 different domains A1, A2, B1, B2.

avatar
C*t
5
Method 1 uses rotation algorithm where no extra space is needed.
Method 2 just does multiple swaps at the same time. No extra space.

【在 h***k 的大作中提到】
: 你这空间不是O(1)吧
:
: we

avatar
C*t
6
Q1.
def swap(nums):
n = len(nums)
for i in range(n):
tmp = origIdx(i, n//2)
while tmp < i: tmp = origIdx(tmp, n//2)
nums[i], nums[tmp] = nums[tmp], nums[i]
print(nums)
def origIdx(cur, n):
return (cur%2)*n + cur//2
avatar
l*u
7
total lengh 2n
index starts from 1
A(i) maps to index 2i-1
B(i) maps to index 2n-2(i-1)

【在 m*****n 的大作中提到】
: 昨天被问了一道老题. array={a1, a2, ..., an, b1, b2, ..., bn}变成 {a1,bn,a2,
: bn-1,...,bn,a0},要求时间复杂度O(N),空间O(1).
: 当时根本不会,我所知道最快的算法是类似quick sort的方法,要O(NlogN), 这个O(N)怎
: 么做? 我记得以前有人贴过,找不到了.
: 还有不用random, time种子什么的, 怎么给shuffle任意一个数组,
: 大概就是
: void shuffle(int A[]){
: }
: 每次出来的 A 的结果不一样.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。