-
238. Product of Array Except SelfAlgorithm/java tip 2021. 3. 24. 00:55
leetcode.com/problems/product-of-array-except-self/
class Solution { public int[] productExceptSelf(int[] nums) { int multiple = 1; boolean isZero = false; int zeroCnt = 0; for(int num : nums) { if(num != 0) { multiple *= num; } if(num == 0) { isZero = true; zeroCnt++; } } int[] ans = new int[nums.length]; if(isZero) { if(zeroCnt > 1) { return ans; } else { for(int i=0; i<nums.length; i++) { if(nums[i] == 0) { ans[i] = multiple; } } } } else { for(int i=0; i<nums.length; i++) { ans[i] = multiple/nums[i]; } } return ans; } }
leetcode.com/problems/product-of-array-except-self/discuss/65638/My-simple-Java-solution
public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; for (int i = 0, tmp = 1; i < nums.length; i++) { result[i] = tmp; tmp *= nums[i]; } for (int i = nums.length - 1, tmp = 1; i >= 0; i--) { result[i] *= tmp; tmp *= nums[i]; } return result; }
'Algorithm > java tip' 카테고리의 다른 글
347. Top K Frequent Elements (0) 2021.03.24 230. Kth Smallest Element in a BST (0) 2021.03.24 198. House Robber (0) 2021.03.23 1387. Sort Integers by The Power Value (0) 2021.03.21 1557. Minimum Number of Vertices to Reach All Nodes (0) 2021.03.20