Created
April 13, 2012 02:10
-
-
Save topin27/2372965 to your computer and use it in GitHub Desktop.
已知数组a,给数组b赋值,b[i]=a[0]*a[1]*...a[N]/a[i],要求时间复杂度为O(n),除了迭代下标,不能另外声明变量,同时不能用除法。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
void foo(int *p_a_, int *p_b_, int n_); | |
int main() | |
{ | |
int a[] = {1, 2, 3, 4, 5}; | |
int b[] = {1, 1, 1, 1, 1}; | |
foo(a, b, 5); | |
for (int i = 0; i < 5; ++i) | |
cout << b[i] << '\t'; | |
cout << endl; | |
} | |
void foo(int *p_a_, int *p_b_, int n_) { | |
p_b_[0] = 1; | |
int i; | |
for (i = 1; i < n_; ++i) { | |
p_b_[i] = p_b_[i - 1] * p_a_[i - 1]; | |
} | |
for (i = n_ - 2; i >= 0; --i) { | |
p_a_[i] *= p_a_[i + 1]; | |
} | |
for (i = 0; i < n_ - 1; ++i) { | |
p_b_[i] *= p_a_[i + 1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment