이 문제는 선형적인 시간과 공간에서 해결하기 쉬워 보입니다. 이 문제는 배열의 기본 개념 중 일부를 기반으로 합니다.
- 배열 순회.
- 접두사와 접미사의 합입니다.
코딩 인터뷰에서 이에 대해 질문한 회사는 Facebook, Amazon, Apple, Netflix, Google, Microsoft, Adobe 및 기타 많은 최고 기술 회사입니다.
문제 진술
정수 배열 nums가 주어지면, 답변[i]가 nums[i]를 제외한 nums의 모든 요소의 곱과 동일하도록 배열 답변을 반환합니다.
nums의 접두사 또는 접미사의 곱은 32비트 정수에 맞도록 보장
됩니다.나누기 연산을 사용하지 않고 O(n) 시간에 실행되는 알고리즘을 작성해야 합니다.
테스트 사례#1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
테스트 사례#2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
문제 이해
이 문제는 선형적인 시간과 공간에서 해결하는 것이 더 간단해 보이지만 의사 코드를 작성하거나 실제 코드 구현을 할 때는 까다롭습니다.
삽화
4개의 요소가 포함된 간단한 배열에서 예상되는 결과를 살펴보겠습니다.
input = {1, 2, 3, 4}
따라서 각 인덱스의 값은 값 자체를 제외한 배열의 다른 모든 요소의 곱입니다. 다음 그림은 이를 보여줍니다.
위의 그림을 바탕으로 공식을 생각해 볼 수 있습니다. 주어진 인덱스 i에 대해 o에서 (i - 1)까지의 요소 곱과 (i 1)에서 (N - 1)까지의 요소 곱을 사용하여 값을 찾을 수 있습니다. 이는 다음 그림에 설명되어 있습니다.
사고 과정
의사 코드를 작성하기 전에 먼저 질문을 떠올리고 면접관에게 물어보세요.
- 중복을 걱정해야 하나요?
- 배열이 비어 있거나 요소가 하나만 있으면 어떻게 되나요? 예상되는 결과는 무엇인가요?
- 배열의 인덱스 중 0 값을 고려/무시해야 합니까? 0을 포함하는 인덱스를 제외하고 다른 모든 값은 0을 갖기 때문입니다.
- 이 문제의 코너/에지 사례는 무엇입니까?
면접관과 위의 질문에 대해 논의한 후 문제 해결을 위한 다양한 접근 방식을 고안해 보세요.
- 순진한 접근 방식/무차별 대입.
- 모든 요소의 산물.
- 좌우 제품
- 접두사 및 접미사 합계.
접근법 1: 순진함/무차별 대입
직관
무차별 접근 방식을 사용하려면 두 개의 for 루프를 실행해야 합니다. 외부 루프 인덱스가 내부 루프 인덱스 값과 일치하면 제품을 건너뛰어야 합니다. 그렇지 않으면 제품을 진행합니다.
연산
- 변수 초기화:
- N = nums.length(입력 배열의 길이).
- result = new int[N] (결과를 저장할 배열).
- 외부 루프(각 요소를 숫자 단위로 반복):
- i = 0 ~ N-1의 경우: currentProduct 초기화 = 1.
- 내부 루프(현재 요소의 곱 계산), j = 0 ~ N-1인 경우:
- i == j인 경우 continue를 사용하여 현재 반복을 건너뜁니다.
- currentProduct에 nums[j]를 곱합니다.
- 현재제품을 결과[i]에 할당합니다.
- 반품 결과.
암호
// brute force static int[] bruteForce(int[] nums) { int N = nums.length; int[] result = new int[N]; for (int i = 0; i <h3> 복잡성 분석 </h3> <ol> <li> <strong>시간 복잡도</strong>: O(n^2), 외부 루프와 내부 루프에서 배열을 두 번 반복합니다.</li> <li> <strong>공간 복잡도</strong>: O(n), 우리가 사용한 보조 공간(결과[] 배열)에 대해.</li> </ol> <h2> 접근법 2: 배열의 곱 ❌ </h2> <p>대부분의 개발자가 생각하는 방법 중 하나는 모든 요소의 곱 합계를 실행하고 곱 합계를 각 배열 값으로 나눈 다음 결과를 반환하는 것입니다.</p> <h3> 유사 코드 </h3> <pre class="brush:php;toolbar:false">// O(n) time and O(1) space p = 1 for i -> 0 to A[i] p * = A[i] for i -> 0 to (N - 1) A[i] = p/A[i] // if A[i] == 0 ? BAM error‼️
암호
// code implementation static int[] productSum(int[] nums) { int product_sum = 1; for(int num: nums) { product_sum *= num; } for(int i = 0; i <p>배열 요소 중 하나에 0이 포함되어 있으면 어떻게 되나요? ?</p> <p>0을 포함하는 인덱스를 제외한 모든 인덱스의 값은 확실히 무한대입니다. 또한 코드에서 java.lang.ArithmeticException이 발생합니다.<br> </p> <pre class="brush:php;toolbar:false">Exception in thread "main" java.lang.ArithmeticException: / by zero at dev.ggorantala.ds.arrays.ProductOfArrayItself.productSum(ProductOfArrayItself.java:24) at dev.ggorantala.ds.arrays.ProductOfArrayItself.main(ProductOfArrayItself.java:14)
접근 방식 3: 접두사 및 접미사 제품 찾기
제 웹사이트 https://ggorantala.dev의 배열 숙달 과정에서 접두사 및 접미사 합에 대해 자세히 알아보세요
직관과 공식
접두사와 접미사는 결과에 대한 알고리즘을 작성하기 전에 계산됩니다. 접두사 및 접미사 합계 공식은 다음과 같습니다.
Algorithm Steps
- Create an array result of the same length as nums to store the final results.
- Create two additional arrays prefix_sum and suffix_sum of the same length as nums.
- Calculate Prefix Products:
- Set the first element of prefix_sum to the first element of nums.
- Iterate through the input array nums starting from the second element (index 1). For each index i, set prefix_sum[i] to the product of prefix_sum[i-1] and nums[i].
- Calculate Suffix Products:
- Set the last element of suffix_sum to the last element of nums.
- Iterate through the input array nums starting from the second-to-last element (index nums.length - 2) to the first element. For each index i, set suffix_sum[i] to the product of suffix_sum[i+1] and nums[i].
- Calculate the result: Iterate through the input array nums.
- For the first element (i == 0), set result[i] to suffix_sum[i + 1].
- For the last element (i == nums.length - 1), set result[i] to prefix_sum[i - 1].
- For all other elements, set result[i] to the product of prefix_sum[i - 1] and suffix_sum[i + 1].
- Return the result array containing the product of all elements except the current element for each index.
Pseudocode
Function usingPrefixSuffix(nums): N = length of nums result = new array of length N prefix_sum = new array of length N suffix_sum = new array of length N // Calculate prefix products prefix_sum[0] = nums[0] For i from 1 to N-1: prefix_sum[i] = prefix_sum[i-1] * nums[i] // Calculate suffix products suffix_sum[N-1] = nums[N-1] For i from N-2 to 0: suffix_sum[i] = suffix_sum[i+1] * nums[i] // Calculate result array For i from 0 to N-1: If i == 0: result[i] = suffix_sum[i+1] Else If i == N-1: result[i] = prefix_sum[i-1] Else: result[i] = prefix_sum[i-1] * suffix_sum[i+1] Return result
Code
// using prefix and suffix arrays private static int[] usingPrefixSuffix(int[] nums) { int[] result = new int[nums.length]; int[] prefix_sum = new int[nums.length]; int[] suffix_sum = new int[nums.length]; // prefix sum calculation prefix_sum[0] = nums[0]; for (int i = 1; i = 0; i--) { suffix_sum[i] = suffix_sum[i + 1] * nums[i]; } for (int i = 0; i <h3> Complexity analysis </h3> <ol> <li> <strong>Time complexity</strong>: The time complexity of the given code is O(n), where n is the length of the input array nums. This is because: <ul> <li>Calculating the prefix_sum products take O(n) time.</li> <li>Calculating the suffix_sum products take O(n) time.</li> <li>Constructing the result array takes O(n) time.</li> </ul> </li> </ol> <p>Each of these steps involves a single pass through the array, resulting in a total time complexity of O(n)+O(n)+O(n) = 3O(n), which is O(n).</p> <ol> <li> <strong>Space complexity</strong>: The space complexity of the given code is O(n). This is because: <ul> <li>The prefix_sum array requires O(n) space.</li> <li>The suffix_sum array requires O(n) space.</li> <li>Theresult array requires O(n) space. All three arrays are of length n, so the total space complexity is O(n) + O(n) + O(n) = 3O(n), which is O(n).</li> </ul> </li> </ol> <h3> Optimization ? </h3> <p>For the suffix array calculation, we override the input nums array instead of creating one.<br> </p> <pre class="brush:php;toolbar:false">private static int[] usingPrefixSuffixOptimization(int[] nums) { int[] result = new int[nums.length]; int[] prefix_sum = new int[nums.length]; // prefix sum calculation prefix_sum[0] = nums[0]; for (int i = 1; i = 0; i--) { nums[i] = nums[i + 1] * nums[i]; } for (int i = 0; i <p>Hence, we reduced the space of O(n). Time and space are not reduced, but we did a small optimization here.</p> <h2> Approach 4: Using Prefix and Suffix product knowledge ? </h2> <h3> Intuition </h3> <p>This is a rather easy approach when we use the knowledge of prefix and suffix arrays.</p> <p>For every given index i, we will calculate the product of all the numbers to the left and then multiply it by the product of all the numbers to the right. This will give us the product of all the numbers except the one at the given index i. Let's look at a formal algorithm that describes this idea more clearly.</p> <h3> Algorithm steps </h3> <ol> <li>Create an array result of the same length as nums to store the final results.</li> <li>Create two additional arrays prefix_sum and suffix_sum of the same length as nums.</li> <li>Calculate Prefix Products: <ul> <li>Set the first element of prefix_sum to 1.</li> <li>Iterate through the input array nums starting from the second element (index 1). For each index i, set prefix_sum[i] to the product of prefix_sum[i - 1] and nums[i - 1].</li> </ul> </li> <li>Calculate Suffix Products: <ul> <li>Set the last element of suffix_sum to 1.</li> <li>Iterate through the input array nums starting from the second-to-last element (index nums.length - 2) to the first element.</li> <li>For each index i, set suffix_sum[i] to the product of suffix_sum[i + 1] and nums[i + 1].</li> </ul> </li> <li>Iterate through the input array nums. <ul> <li>For each index i, set result[i] to the product of prefix_sum[i] and suffix_sum[i].</li> </ul> </li> <li>Return the result array containing the product of all elements except the current element for each index.</li> </ol> <h3> Pseudocode </h3> <pre class="brush:php;toolbar:false">Function prefixSuffix1(nums): N = length of nums result = new array of length N prefix_sum = new array of length N suffix_sum = new array of length N // Calculate prefix products prefix_sum[0] = 1 For i from 1 to N-1: prefix_sum[i] = prefix_sum[i-1] * nums[i-1] // Calculate suffix products suffix_sum[N-1] = 1 For i from N-2 to 0: suffix_sum[i] = suffix_sum[i+1] * nums[i+1] // Calculate result array For i from 0 to N-1: result[i] = prefix_sum[i] * suffix_sum[i] Return result
Code
private static int[] prefixSuffixProducts(int[] nums) { int[] result = new int[nums.length]; int[] prefix_sum = new int[nums.length]; int[] suffix_sum = new int[nums.length]; prefix_sum[0] = 1; for (int i = 1; i = 0; i--) { suffix_sum[i] = suffix_sum[i + 1] * nums[i + 1]; } for (int i = 0; i <h3> Complexity analysis </h3> <ol> <li> <strong>Time complexity</strong>: The time complexity of the given code is O(n), where n is the length of the input array nums. This is because: <ul> <li>Calculating the prefix_sum products take O(n) time.</li> <li>Calculating the suffix_sum products take O(n) time.</li> <li>Constructing the result array takes O(n) time.</li> </ul> </li> </ol> <p>Each of these steps involves a single pass through the array, resulting in a total time complexity of O(n)+O(n)+O(n) = 3O(n), which is O(n).</p> <ol> <li> <strong>Space complexity</strong>: The space complexity of the given code is O(n). This is because: <ul> <li>The prefix_sum array requires O(n) space.</li> <li>The suffix_sum array requires O(n) space.</li> <li>The result array requires O(n) space.</li> </ul> </li> </ol> <p>All three arrays are of length n, so the total space complexity is O(n) + O(n) + O(n) = 3O(n), which is O(n).</p> <h2> Approach 5: Carry Forward technique </h2> <h3> Intuition </h3> <p>The carry forward technique optimizes us to solve the problem with a more efficient space complexity. Instead of using two separate arrays for prefix and suffix products, we can use the result array itself to store intermediate results and use a single pass for each direction.</p> <p>Here’s how you can implement the solution using the carry-forward technique:</p> <h3> Algorithm Steps for Carry Forward Technique </h3> <ol> <li>Initialize Result Array: <ul> <li>Create an array result of the same length as nums to store the final results.</li> </ul> </li> <li>Calculate Prefix Products: <ul> <li>Initialize a variable prefixProduct to 1.</li> <li>Iterate through the input array nums from left to right. For each index i, set result[i] to the value of prefixProduct. Update prefixProduct by multiplying it with nums[i].</li> </ul> </li> <li>Calculate Suffix Products and Final Result: <ul> <li>Initialize a variable suffixProduct to 1.</li> <li>Iterate through the input array nums from right to left. For each index i, update result[i] by multiplying it with suffixProduct. Update suffixProduct by multiplying it with nums[i].</li> </ul> </li> <li>Return the result array containing the product of all elements except the current element for each index.</li> </ol> <h3> Pseudocode </h3> <pre class="brush:php;toolbar:false">prefix products prefixProduct = 1 For i from 0 to N-1: result[i] = prefixProduct prefixProduct = prefixProduct * nums[i] // Calculate suffix products and finalize result suffixProduct = 1 For i from N-1 to 0: result[i] = result[i] * suffixProduct suffixProduct = suffixProduct * nums[i] Return result
Code
// carry forward technique private static int[] carryForward(int[] nums) { int n = nums.length; int[] result = new int[n]; // Calculate prefix products int prefixProduct = 1; for (int i = 0; i = 0; i--) { result[i] *= suffixProduct; suffixProduct *= nums[i]; } return result; }
Explanation
- Prefix Products Calculation:
- We initialize prefixProduct to 1 and update each element of result with the current value of prefixProduct.
- Update prefixProduct by multiplying it with nums[i].
- Suffix Products Calculation:
- We initialize suffixProduct to 1 and update each element of result(which already contains the prefix product) by multiplying it with suffixProduct.
- Update suffixProduct by multiplying it with nums[i].
Complexity analysis
- Time Complexity: O(n) time
- Space Complexity: O(n) (for the result array)
This approach uses only a single extra array (result) and two variables (prefixProduct and suffixProduct), achieving efficient space utilization while maintaining O(n) time complexity.
위 내용은 Leetcode : 자기를 제외한 배열의 곱의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Java는 플랫폼 독립성으로 인해 엔터프라이즈 수준의 응용 프로그램에서 널리 사용됩니다. 1) 플랫폼 독립성은 JVM (Java Virtual Machine)을 통해 구현되므로 JAVA를 지원하는 모든 플랫폼에서 코드가 실행될 수 있습니다. 2) 크로스 플랫폼 배포 및 개발 프로세스를 단순화하여 유연성과 확장 성을 더 많이 제공합니다. 3) 그러나 성능 차이 및 타사 라이브러리 호환성에주의를 기울이고 순수한 Java 코드 사용 및 크로스 플랫폼 테스트와 같은 모범 사례를 채택해야합니다.

javaplaysaSignificantroleiniotduetoitsplatformincentence.1) itallowscodetobewrittenonceandevices.2) java'secosystemprovidesusefullibrariesforiot.3) itssecurityfeaturesenhanceiotiotsystemsafety.hormormory.hormory.hustupletety.houghmormory

thejava.nio.filepackage.1) withsystem.getProperty ( "user.dir") andtherelativeatthereplattHefilePsiple.2) thepathtopilebtoafne 컨버터링 주제

Java'SplatformIndenceSnictIficantIficantBecauseItAllowsDeveloperstowRiteCodeOnceAntOnitonAnyplatformwithajvm.이 "WriteOnce, Runanywhere"(WORA) 접근자 : 1) 교차 플랫폼 컴퓨팅 성, DeploymentAcrossDifferentoSwithoutissswithoutissuesswithoutissuesswithoutswithoutisssues를 활성화합니다

Java는 크로스 서버 웹 응용 프로그램을 개발하는 데 적합합니다. 1) Java의 "Write Once, Run Everywhere"철학은 JVM을 지원하는 모든 플랫폼에서 코드를 실행합니다. 2) Java는 Spring 및 Hibernate와 같은 도구를 포함하여 개발 프로세스를 단순화하는 풍부한 생태계를 가지고 있습니다. 3) Java는 성능 및 보안에서 훌륭하게 성능을 발휘하여 효율적인 메모리 관리 및 강력한 보안 보증을 제공합니다.

JVM은 바이트 코드 해석, 플랫폼 독립 API 및 동적 클래스 로딩을 통해 Java의 Wora 기능을 구현합니다. 1. 바이트 코드는 크로스 플랫폼 작동을 보장하기 위해 기계 코드로 해석됩니다. 2. 표준 API 추상 운영 체제 차이; 3. 클래스는 런타임에 동적으로로드되어 일관성을 보장합니다.

JAVA의 최신 버전은 JVM 최적화, 표준 라이브러리 개선 및 타사 라이브러리 지원을 통해 플랫폼 별 문제를 효과적으로 해결합니다. 1) Java11의 ZGC와 같은 JVM 최적화는 가비지 수집 성능을 향상시킵니다. 2) Java9의 모듈 시스템과 같은 표준 라이브러리 개선은 플랫폼 관련 문제를 줄입니다. 3) 타사 라이브러리는 OpenCV와 같은 플랫폼 최적화 버전을 제공합니다.

JVM의 바이트 코드 검증 프로세스에는 네 가지 주요 단계가 포함됩니다. 1) 클래스 파일 형식이 사양을 준수하는지 확인, 2) 바이트 코드 지침의 유효성과 정확성을 확인하고 3) 유형 안전을 보장하기 위해 데이터 흐름 분석을 수행하고 4) 검증의 철저한 성능 균형을 유지합니다. 이러한 단계를 통해 JVM은 안전하고 올바른 바이트 코드 만 실행되도록하여 프로그램의 무결성과 보안을 보호합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

드림위버 CS6
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.