【Lintcode】1415. Residual Product
題目地址:
https://www.lintcode.com/problem/residual-product/description
給定一個陣列 A A A,返回一個新陣列 B B B,使得 B [ i ] = ∏ j ≠ i A [ j ] B[i]=\prod_{j\ne i}A[j] B[i]=∏j=iA[j]。如果 A A A長度是 1 1 1則返回零陣列。
參考https://blog.csdn.net/qq_46105170/article/details/108656955。程式碼如下:
public class Solution {
/**
* @param arr: The array you should handle
* @return: Return the product
*/
public int[] getProduct(int[] arr) {
// Write your code here
int[] res = new int[arr.length];
if (arr.length == 1) {
return res;
}
long prod = 1;
int zeroCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
prod *= arr[i];
} else {
zeroCount++;
}
}
if (zeroCount == 1) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
res[i] = (int) prod;
} else {
res[i] = 0;
}
}
} else if (zeroCount == 0) {
for (int i = 0; i < arr.length; i++) {
res[i] = (int) (prod / arr[i]);
}
}
return res;
}
}
時間複雜度 O ( l A ) O(l_A) O(lA),空間 O ( 1 ) O(1) O(1)。
相關文章
- 【Lintcode】191. Maximum Product Subarray
- 【Lintcode】1322. Product Equal B
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- Product Quantization
- A. Least ProductAST
- 殘差網路(Residual Networks, ResNets)
- 1415. [NOIP2001]數的計數
- [論文閱讀] Residual Attention(Multi-Label Recognition)
- Leetcode Maximum Product SubarrayLeetCode
- ABC 322 E Product Developmentdev
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- SAP EPD - Enterprise Product Developmentdev
- Get your Windows product key from a scriptWindows
- Leetcode-Maximum Product SubarrayLeetCode
- Error accessing PRODUCT_USER_PROFILEError
- LeetCode:Product of Array Except SelfLeetCode
- Product_user_profile(PUP) TABLE FOR security
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree
- LintCode-Partition Array
- LintCode-Subarray Sum
- LintCode-Majority Number
- LintCode-A+B Problem
- LintCode-BackPack II
- LintCode-Previous Permuation
- LintCode 字串比較字串
- Hackerrank GCD Product(莫比烏斯反演)GC
- LeetCode-Maximum Product of Word LengthsLeetCode