search
HomeBackend DevelopmentPHP Problemphp exclude current element from product array

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;
}

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
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

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool