zoukankan      html  css  js  c++  java
  • #Leetcode# 238. Product of Array Except Self

    https://leetcode.com/problems/product-of-array-except-self/

    Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Example:

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

    Note: Please solve it without division and in O(n).

    Follow up:
    Could you solve it with constant space complexity? (The output array does notcount as extra space for the purpose of space complexity analysis.)

    代码:

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            int cnt = 0;
            vector<int> ans;
            for(int i = 0; i < n; i ++) {
                if(nums[i] == 0) cnt ++;
            }
            if(cnt == n) {
                for(int i = 0; i < n; i ++)
                    ans.push_back(0);
                return ans;
            }
            
            int t = 1, tt = 1;
            for(int i = 0; i < n; i ++) {
                if(nums[i] != 0) tt *= nums[i];
                t *= nums[i];
            }
                
            for(int i = 0; i < n; i ++) {
                if(nums[i] == 0) {
                    if(cnt == 1) ans.push_back(tt);
                    else ans.push_back(0);
                }
                    
                else ans.push_back(t / nums[i]);
            }
                
            return ans;
        }
    };
    

      

  • 相关阅读:
    CSS 层叠样式表
    一. 图论
    二. log4j配置文件
    三.注解
    3. Map与Tuple
    MappedByteBuffer读写文件
    2. scala中的数组
    1.scala语法
    二. 模式匹配
    一.算法的数学基础
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10708455.html
Copyright © 2011-2022 走看看