この問題は線形時間と空間で解くのが簡単そうに見えます。この問題は、配列の基本的な概念のいくつかに基づいています。
- 配列の走査。
- プレフィックスとサフィックスの合計。
コーディング面接でこの質問をした企業は、Facebook、Amazon、Apple、Netflix、Google、Microsoft、Adobe、その他多くのトップテクノロジー企業です。
問題文
整数配列 nums を指定すると、answer[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) までの要素の積を使用して値を見つけることができます。これを次の図に示します。
思考プロセス
疑似コードを書く前に、質問を考えて面接官に質問してください。
- 重複について心配する必要がありますか?
- 配列が空であるか、要素が 1 つしかない場合はどうなりますか?期待される結果は何ですか?
- 配列内のインデックスのいずれかの値が 0 であることを考慮/無視する必要がありますか? 0 を含むインデックスを除き、他のすべての値は 0 になるためです。
- この問題のコーナー/エッジケースは何ですか?
あなたと面接官が上記の質問について話し合ったら、問題を解決するためのさまざまなアプローチを考案してください。
- 素朴なアプローチ/強引。
- すべての要素の積。
- 左右の商品です。
- プレフィックスとサフィックスの合計。
アプローチ 1: ナイーブ/ブルートフォース
直感
総当たりアプローチを採用するには、2 つの for ループを実行する必要があります。外側のループのインデックスが内側のループのインデックス値と一致する場合、積をスキップする必要があります。それ以外の場合は、製品を続行します。
アルゴリズム
- 変数を初期化します:
- N = nums.length (入力配列の長さ).
- result = new int[N] (結果を保存する配列).
- 外側のループ (nums 内の各要素を反復処理):
- i = 0 ~ N-1 の場合: currentProduct = 1 を初期化します。
- 内部ループ (現在の要素の積を計算)、j = 0 ~ N-1 の場合:
- i == j の場合、Continue を使用して現在の反復をスキップします。
- currentProduct に nums[j] を掛けます。
- currentProduct を result[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)、外側ループと内側ループで配列を 2 回繰り返す場合。</li> <li> <strong>空間複雑度</strong>: O(n)、使用した補助空間 (result[] 配列)。</li> </ol> <h2> アプローチ 2: 配列の積 ❌ </h2> <p>ほとんどの開発者が考える 1 つの方法は、すべての要素の積和を実行し、その積和を各配列値で除算して、結果を返すことです。</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>配列要素の 1 つに 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: プレフィックスとサフィックスの積を検索する
プレフィックスとサフィックスの合計について詳しくは、私の Web サイト 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 : Self を除く配列の積の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Javaは、プラットフォームの独立性により、エンタープライズレベルのアプリケーションで広く使用されています。 1)プラットフォームの独立性は、Java Virtual Machine(JVM)を介して実装されているため、Javaをサポートする任意のプラットフォームでコードを実行できます。 2)クロスプラットフォームの展開と開発プロセスを簡素化し、柔軟性とスケーラビリティを高めます。 3)ただし、パフォーマンスの違いとサードパーティライブラリの互換性に注意を払い、純粋なJavaコードやクロスプラットフォームテストの使用などのベストプラクティスを採用する必要があります。

javaplaysasificanificantduetduetoitsplatformindepence.1)itallowscodetobewrittendunonvariousdevices.2)java'secosystemprovidesutionforiot.3)そのセキュリティフィートルセンハンス系

TheSolution to HandlefilepathsaCrosswindossandlinuxinjavaistousepaths.get()fromthejava.nio.filepackage.1)usesystem.getProperty( "user.dir")およびhearterativepathtoconstructurctthefilepath.2)

java'splatformentepenceissificAntiveSifcuseDeverowsDevelowSowRitecodeOdeonceantoniTONAnyPlatformwsajvm.これは「writeonce、runanywhere」(wora)adportoffers:1)クロスプラットフォームの複雑性、deploymentacrossdiferentososwithusisues; 2)re

Javaは、クロスサーバーWebアプリケーションの開発に適しています。 1)Javaの「Write and、Run Averywhere」哲学は、JVMをサポートするあらゆるプラットフォームでコードを実行します。 2)Javaには、開発プロセスを簡素化するために、SpringやHibernateなどのツールを含む豊富なエコシステムがあります。 3)Javaは、パフォーマンスとセキュリティにおいて優れたパフォーマンスを発揮し、効率的なメモリ管理と強力なセキュリティ保証を提供します。

JVMは、バイトコード解釈、プラットフォームに依存しないAPI、動的クラスの負荷を介してJavaのWORA機能を実装します。 2。標準API抽象オペレーティングシステムの違い。 3.クラスは、実行時に動的にロードされ、一貫性を確保します。

Javaの最新バージョンは、JVMの最適化、標準的なライブラリの改善、サードパーティライブラリサポートを通じて、プラットフォーム固有の問題を効果的に解決します。 1)Java11のZGCなどのJVM最適化により、ガベージコレクションのパフォーマンスが向上します。 2)Java9のモジュールシステムなどの標準的なライブラリの改善は、プラットフォーム関連の問題を削減します。 3)サードパーティライブラリは、OpenCVなどのプラットフォーム最適化バージョンを提供します。

JVMのバイトコード検証プロセスには、4つの重要な手順が含まれます。1)クラスファイル形式が仕様に準拠しているかどうかを確認し、2)バイトコード命令の有効性と正確性を確認し、3)データフロー分析を実行してタイプの安全性を確保し、検証の完全性とパフォーマンスのバランスをとる。これらの手順を通じて、JVMは、安全で正しいバイトコードのみが実行されることを保証し、それによりプログラムの完全性とセキュリティを保護します。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 中国語版
中国語版、とても使いやすい

メモ帳++7.3.1
使いやすく無料のコードエディター

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。
