【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)。
相關文章
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- 【Lintcode】1322. Product Equal B
- 【Lintcode】191. Maximum Product Subarray
- 關於Residual Connection
- Product Quantization
- 殘差網路(Residual Networks, ResNets)
- A. Least ProductAST
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- ABC 322 E Product Developmentdev
- SAP EPD - Enterprise Product Developmentdev
- [論文閱讀] Residual Attention(Multi-Label Recognition)
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- 238. Product of Array Except Self
- LeetCode | 152. Maximum Product SubarrayLeetCode
- 318-Maximum Product of Word Lengths
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI
- 【Lintcode】318. Character Grid
- 【Lintcode】1891. Travel Plan