[LeetCode] 238. Product of Array Except Self

2021. 6. 6. 16:59·알고리즘 문제풀이/LeetCode
728x90

문제

1차원 배열 nums가 주어졌을 때, 다음을 만족하는 배열 answer를 리턴하라.

answer[i]는 nums[i]를 제외한 요소의 모든 곱이다.

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

풀이

나누기 연산을 사용하지 않는 조건이기 때문에, 다른 방법을 생각해야 한다.

각 answer[i] 마다 nums[i]를 제외한 요소들을 모두 곱하는 경우 O(n*n)으로 Time Limit Exceeded가 된다.

 

배열 nums가 [1, 2, 3, 4]인 경우 nums [i]를 제외한 요소들을 확인해보자.

answer[1]는 2의 left에 있는 [1]과 right에 있는 [3, 4]를 곱한 수이고

answer[2]는 3의 left에 있는 [1, 2]과 right에 있는 [4]를 곱한 수이다.

 

left만 확인해보면 answer[1] = 1, answer[2] = 1*2, answer[3] = 1*2*3 인 것을 볼 수 있다.

다시 말해서, answer[i] = answer[i - 1] * nums[i - 1] 가 된다.

answer[0]은 left가 없기 때문에 1을 대입하면 된다.

 

right만 보면 answer[2] = 4, answer[1] = 4*3, answer[0] = 4*3*2 이다.

다시 말해서, answer[i] = answer[i + 1] * nums[i + 1] 가 된다.

 

따라서 left와 right를 곱한 값을 answer에 저장하는 것이므로

left를 answer[i]에 각각 저장하고

right는 따로 right 변수를 하나 생성하여 answer[i]에 right를 곱하고, 그다음 계산을 위해 right *= nums[i]를 하며 반복하면 된다.

 

코드

public class leetcode_238 {
    static public int[] productExceptSelf(int[] nums) {

        int len = nums.length;
        int[] answer = new int[len];

        answer[0] = 1;
        for (int i = 1; i < len; i++) {
            answer[i] = nums[i - 1] * answer[i - 1];
            System.out.println(answer[i]);
        }

        int right = 1;
        for (int i = len - 1; i >= 0; i--) {
            answer[i] *= right;
            right *= nums[i];
        }

        return answer;
    }

    public static void main(String[] args) {
        int[] temp = {1, 2, 3, 4};
        System.out.println();
        for (int num : productExceptSelf(temp)) {
            System.out.println(num);
        }
    }

}
728x90

'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글

[LeetCode] 70. Climbing Stairs  (0) 2021.06.10
[LeetCode] 322. Coin Change  (1) 2021.06.10
[LeetCode] 217. Contains Duplicate  (0) 2021.06.06
[LeetCode] 121. Best Time to Buy and Sell Stock  (0) 2021.06.06
[LeetCode] 1. Two Sum  (0) 2021.06.03
'알고리즘 문제풀이/LeetCode' 카테고리의 다른 글
  • [LeetCode] 70. Climbing Stairs
  • [LeetCode] 322. Coin Change
  • [LeetCode] 217. Contains Duplicate
  • [LeetCode] 121. Best Time to Buy and Sell Stock
kiminae
kiminae
공부한 내용을 정리합니다.
  • kiminae
    데이터 다루는 사람
    kiminae
  • 전체
    오늘
    어제
    • 분류 전체보기 (67)
      • AI & 빅데이터 (6)
        • kafka (10)
        • [Book] 빅데이터를 지탱하는 기술 (12)
      • 알고리즘 (19)
      • 알고리즘 문제풀이 (13)
        • programmers (0)
        • 백준 (1)
        • LeetCode (12)
      • Android (3)
      • Book&Lesson (13)
        • [Lesson] 프로그래머스 커뮤러닝 (Pyth.. (1)
      • 참고한 글들 (1)
      • 컨퍼런스 정리 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    데이터시각화
    버블정렬
    leetcode
    mvvm
    리트코드
    알고리즘문제
    Kafka
    알고리즘풀이
    hadoop
    MPP데이터베이스
    추천알고리즘
    DP문제
    ViewModel
    파이프라인구축
    sort
    시간복잡도
    Algorithm
    정렬
    빅데이터
    BI도구
    카프카클라이언트
    카프카
    정렬알고리즘
    데이터엔지니어
    머신러닝
    빅데이터를지탱하는기술
    릿코드
    알고리즘
    트리
    개인화추천
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
kiminae
[LeetCode] 238. Product of Array Except Self
상단으로

티스토리툴바