NVDIA(英伟达)一道笔试笔试编程题
Given an integer number N(n = m^2 - 1),
print sequence 0, 1, 2, 3, ..., n,in below form.
You can only use printf(C) or cout(C++).
For example, given n = 24(5^2 - 1), the program should output
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
1. What memory & computation complexity of your algorithm?
//你的算法的时间和空间的复杂度?
2. Is there an algorithm to get O(1) of memory and O(n) of computation complexity
//有没有空间复杂度为O(1),而时间复杂度为O(n)的算法?
分析:
0 1 2 3 4
15 0 1 2 5
14 7 0 3 6
13 6 5 4 7
12 11 10 9 8
1. 空间复杂度和时间复杂度都是O(n)的算法的实现如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100000
void screw(int*a, int n);
void printArray(int*a, int n);
int main(int argc, char* argv[], char* env[])
{
int a[MAX] = {0,};
int i;
int n;
for(i=1; i<10; i++) {
n = i*i -1;
screw(a, n);
printArray(a, n);
}
return 0;
}
void screw(int* a, int n) {
int m;
int p;
int q;
int i;
int j;
int k;
int base;
m = (int)sqrt(n+1);
q = 0;
k = 0;
for(p=m; p>0; p-=2) {
base = m*q + q;
//上边
j=0;
for(i=0; i<p; i++) {
a[base+j*m+i] = k++;
}
//右边
i=p-1;
for(j=1; j<p; j++) {
a[base+j*m+i] = k++;
}
//下边
j=p-1;
for(i=p-2; i>=0; i--){
a[base+j*m+i] = k++;
}
//左边
i=0;
for(j=p-2; j>0; j--) {
a[base+j*m+i] = k++;
}
q++;
}
}
void printArray(int * a, int n) {
int i;
int m;
m = (int)sqrt(n+1);
for(i=0; i<=n; i++) {
if(i%m == 0) printf("\n");
printf("%2d ", a[i]);
}
printf("\n");
}
运行结果:
2.是否有空间复杂度为O(1), 计算法复杂度为O(n)的算法?
//怎么求逆函数,思考中ing。。