vendredi 25 août 2023

Didn't getting the modern C++ syntax, just wanting to know what they mean and how it works on dry run with this LeetCode problem [closed]

Problem statement :

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:

Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2:

Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]

Solution :

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int prod = 1, zeroCnt = count(begin(nums), end(nums), 0);
        if(zeroCnt > 1) return vector<int>(size(nums));               // Case-1
        for(auto c : nums) 
            if(c) prod *= c;                                          // calculate product of all elements except 0
        for(auto& c : nums)
            if(zeroCnt) c = c ? 0 : prod;                             // Case-2
            else c = prod / c;                                        // Case-3
        return nums;
    }
};

*Didn't get what is return vector<int>(size(nums)); and how it works why not return vector<int>v(size(nums));.

*Also, please explain what is auto keyword, what is its use in here i.e. mainly I'm asking about the auto keyword like what is for(auto c : nums) and how it works ?

*what is : in for(auto c : nums)

*What is for(auto& c : nums) and how it works i.e. what is & here ?

*What is if(c) and how it works ?

*Please explain this line i.e. if(zeroCnt) c = c ? 0 : prod; what is ? here ?

Aucun commentaire:

Enregistrer un commentaire