Given an array nums. Find an array output array such that output[i] is equal to the product of all the elements of nums except nums[i]
Example:
Input: arr[]={1,2,3,4} Output: arr[]={24,12,8,6}
Approach
Java
import java.util.Arrays;public class ProductExceptSelf {public static void main(String[] args) {int arr[] = { 1, 2, 3, 4};productExceptSelf(arr);for (int i = 0; i < arr.length; i++)System.out.print(arr[i] + " ");}// method to find the product// of array except selfprivate static void productExceptSelf(int[] arr) {int n = arr.length;int left[] = new int[n];int right[] = new int[n];Arrays.fill(left, 1);Arrays.fill(right, 1);// product of left of given positionfor (int i = 1; i < n; i++)left[i] = left[i - 1] * arr[i - 1];// product of right of given positionfor (int i = n - 2; i >= 0; i--)right[i] = right[i + 1] * arr[i + 1];// final product except selffor (int i = 0; i < n; i++)arr[i] = left[i] * right[i];}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the product//of array except selftvector<int> productExceptSelf(vector<int>& nums){int n=nums.size();vector<int> left,right;left.resize(n,1);right.resize(n,1);//product of left of given positionfor(int i=1;i<n;i++)left[i]=left[i-1]*nums[i-1];//product of right of given positionfor(int i=n-2;i>=0;i--)right[i]=right[i+1]*nums[i+1];//final product except selffor(int i=0;i<n;i++)nums[i]=left[i]*right[i];return nums;}int main(){vector<int> arr={1,2,3,4};arr=productExceptSelf(arr);for(int i=0;i<arr.size();i++)cout<<arr[i]<<" ";return 0;}
No comments:
Post a Comment