Home Backend Development PHP Problem php exclude current element from product array

php exclude current element from product array

May 19, 2023 pm 05:45 PM

PHP is a widely used scripting language commonly used in the field of web development. In PHP, we often encounter situations where arrays need to be processed. For example, given an array, it is required to calculate the product of the remaining elements after removing the current element. This article will introduce how to use PHP to implement the product array after removing the current element.

1. Original idea:

We can use two loops to complete this requirement:

  • The outer loop traverses each element
  • The inner loop calculates the product of elements other than the current element being traversed

However, the time complexity of this method is O(n^2). When there are too many array elements, the program execution time will increase significantly. Therefore, we need to change our thinking to improve algorithm efficiency.

2. Optimization idea:

We can first calculate the product of the entire array, and then divide the product of the entire array by the current element based on the current element to get the product after removing the current element. product.

However, this method will cause problems when the current element is 0, because dividing by 0 is meaningless. Therefore, we need to handle the case where the current element is 0.

3. Complete code:

The complete PHP code is given below:

function productExceptSelf($nums) {
    $length = count($nums);
    if ($length == 0) {
        return array();
    } elseif ($length == 1) {
        return array(0);
    }

    $prod = 1;
    $zeroCount = 0;
    for ($i = 0; $i < $length; $i++) {
        if ($nums[$i] == 0) {
            $zeroCount++;
            if ($zeroCount > 1) {
                return array_fill(0, $length, 0);
            }
            continue;
        }
        $prod *= $nums[$i];
    }

    $res = array();
    for ($i = 0; $i < $length; $i++) {
        if ($zeroCount == 1 && $nums[$i] != 0) {
            $res[] = 0;
            continue;
        }
        if ($zeroCount > 1) {
            $res[] = 0;
            continue;
        }
        $res[] = $nums[$i] == 0 ? $prod : $prod / $nums[$i];
    }
    return $res;
}
Copy after login

4. Code analysis:

The above code adopts the following ideas: First, scan the entire array and calculate the product of the non-zero elements in the array. At the same time, record the number of 0s in the array. Secondly, the entire array is scanned, and for each element, the final result is calculated based on the above total product and the number of 0s.

Among them, if the current element is 0, special processing is adopted. If the number of 0s in the array is greater than 1, an array in which all elements are 0 is directly returned, otherwise the product of the current elements is 0.

5. Test case:

The following are several sets of test data:

$nums = [1, 2, 3, 4];
echo implode(" ,", productExceptSelf($nums)); // Output "24,12,8,6"

$nums = [0, 2, 3, 4];
echo implode("," , productExceptSelf($nums)); // Output "24,0,0,0"

$nums = [1, 0, 3, 4];
echo implode(",", productExceptSelf ($nums)); // Output "0,12,0,0"

$nums = [1, 0, 3, 0];
echo implode(",", productExceptSelf($ nums)); // Output "0,0,0,0"

6. Summary:

This article introduces how to use PHP to implement the product array after removing the current element. Through optimization algorithms, the time complexity of the program can be effectively reduced and the execution efficiency of the program can be improved. In actual development, we should choose the optimal algorithm to process arrays according to the specific situation.

The above is the detailed content of php exclude current element from product array. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24