Problem Solving 2022. 7. 31. 22:13

[LeetCode] 238. Product of Array Except Self (JS)

목차
  1. 핵심 아이디어
  2. 복잡도
  3. 설명
  4. 코드 (Javascript)

https://leetcode.com/problems/product-of-array-except-self/

 

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

핵심 아이디어

  • result[i]의 값은 왼쪽 부분(prefix)의 곱과 오른쪽 부분(postfix)의 곱을 곱한 것이다
    • prefix[i]와 postfix[i] 는 각자 이전 값에다 nums[i]를 곱하면 되기 때문에 O(1) 시간에 구할 수 있다
  • result array에 prefix 값을 쓰고, 다시 반대로 읽으면서 postfix 값을 쓰면서 공간 복잡도를 O(1)으로 줄일 수 있다
    • result array는 어차피 답 출력할 때 써야 하는 array이므로 공간 복잡도 계산에 포함되지 않는다

 

복잡도

  • 시간 복잡도: O(n)
    • 배열을 순방향, 역방향으로 2회 순회
    • 이전 값에 누적하며 곱하는 방식으로 prefix 구하기 O(n) + 반대 방향으로 postfix 곱하면서 채우기 O(n)
  • 공간 복잡도: O(1)
    • 출력할 때 쓰는 result array를 활용 (공간 복잡도 계산 x)
    • prefix 변수 O(1), postfix 변수 O(1)

 

설명

 

 

코드 (Javascript)

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function(nums) {
    let result = Array(nums.length);
    
    let prefixProduct = 1;
    for (let i = 0; i < nums.length; i++) {
        result[i] = prefixProduct;
        prefixProduct *= nums[i];
    }
    
    let postfixProduct = 1;
    for (let i = nums.length - 1; i >= 0; i--) {
        result[i] *= postfixProduct;
        postfixProduct *= nums[i];
    }
    
    return result;
};

 

유튜브 NeetCode 해설 영상

 

저작자표시 (새창열림)

'Problem Solving' 카테고리의 다른 글

[LeetCode] 152. Maximum Product Subarray (JS)  (0) 2022.08.21
[LeetCode] 53. Maximum Subarray (JS)  (0) 2022.08.07
[LeetCode] 217. Contains Duplicate (JS)  (0) 2022.07.31
[LeetCode] 121. Best Time to Buy and Sell Stock (JS)  (0) 2022.07.02
[LeetCode] 1. Two Sum (JS)  (0) 2022.07.02
  1. 핵심 아이디어
  2. 복잡도
  3. 설명
  4. 코드 (Javascript)
'Problem Solving' 카테고리의 다른 글
  • [LeetCode] 152. Maximum Product Subarray (JS)
  • [LeetCode] 53. Maximum Subarray (JS)
  • [LeetCode] 217. Contains Duplicate (JS)
  • [LeetCode] 121. Best Time to Buy and Sell Stock (JS)
이우진 기술 블로그개발자 이우진의 기술 블로그입니다
개발자 이우진
이우진 기술 블로그
  • All (86)
    • Spring Framework (20)
    • MSA (7)
      • Event Driven Architecture (3)
    • Java (3)
    • Flink (2)
    • Computer Science (9)
      • Object Oriented Programming (3)
    • Problem Solving (15)
    • Design Pattern (0)
    • React (4)
    • Javascript (2)
    • Web (3)
    • Tools & Environment (3)
    • C++ (2)
    • misc (5)
    • Essay (3)
      • 기술 회고 (5)
  • 홈
  • 태그
  • 관리자
  • 글쓰기
hELLO · Designed By 정상우.v4.2.2
[LeetCode] 238. Product of Array Except Self (JS)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.