[LeetCode] Product of Array Except Self
2020. 1. 4. 00:51ㆍ알고리즘
Product of Array Except Self - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
DP처럼 문제를 해결하면 된다! 해당 인덱스를 제외한 곱을 구하기 위해 왼쪽 곱과 오른쪽 곱을 구하고 이를 이용해 결과를 만들면 된다.
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> answer(n);
int leftProduct = 1;
for (int i = 0; i < n; i++) {
answer[i] = leftProduct;
leftProduct *= nums[i];
}
int rightProduct = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= rightProduct;
rightProduct *= nums[i];
}
return answer;
}
};
'알고리즘' 카테고리의 다른 글
[LeetCode] Top K Frequent Elements (0) | 2019.12.31 |
---|---|
[LeetCode] Generate Parentheses (0) | 2019.12.30 |
[LeetCode] Permutations (0) | 2019.12.23 |
[LeetCode] Binary Tree Inorder Traversal (0) | 2019.12.21 |
[프로그래머스] 단어 변환 (0) | 2019.10.30 |