第43天。
今天的题目是Product of Array Except Self:
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up: Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
这里说不能使用除法,我的想法就是自己实现一个除法:
1int Div(unsigned a,unsigned b) {2 int x,y;3 int ans = 0;4 while(a >= b) {5 x = b;6 y = 1;7 while( a >= (x<<1)) {8 x <<= 1;9 y <<= 1;10 }11 a -= x;12 ans += y;13 }14 return ans;15}6 collapsed lines
16int div(int a,int b) {17 if (a > 0 && b > 0) return Div(a,b);18 else if (a < 0 && b < 0) return Div(-a,-b);19 else if (a < 0) return -Div(-a,b);20 else return -Div(a,-b);21}
然后剩下的东西就是将0
这个特例排除掉了:
1vector<int> productExceptSelf(vector<int>& nums) {2 vector<int> ret(nums.size(),0);3 long long product = 1;4 int zero_count = 0;5 for(auto i:nums)6 if (i != 0) product*=i;7 else zero_count++;8 cout << zero_count << endl;9
10 if (zero_count > 1) return ret;11
12 if (zero_count == 1) {13 for(int i = 0;i < nums.size();i++) {14 if (nums[i] != 0) ret[i] = 0;15 else ret[i] = product;10 collapsed lines
16 }17 return ret;18 }19
20 for(int i = 0;i < ret.size();i++) {21 // if (nums[i] == 0) ret[i] = product[i];22 ret[i] = div((int)product,nums[i]);23 }24 return ret;25}
但是看了dicuss
的做法,我感觉的理解是错的:
1def productExceptSelf(self, nums):2 p = 13 n = len(nums)4 output = []5 for i in range(0,n):6 output.append(p)7 p = p * nums[i]8 p = 19 for i in range(n-1,-1,-1):10 output[i] = output[i] * p11 p = p * nums[i]12 return output
恩,今天写的有点急,因为我周五安全导论还要考试,然而我还一堆东西不会。。。