zoukankan      html  css  js  c++  java
  • leetcode [238. 除自身以外数组的乘积]

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

    感觉最近的每日一题都挺好玩的,静下心好好想想能体会到久违的思考的乐趣:)

    方法一:就是开两个数组,每个数组存前缀积和后缀积,用到的时候直接拿出来相乘就行了

    class Solution {
    public:
        vector<int> ad1,ad2,ans;
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            ad1.resize(n+1);ad2.resize(n+1);
            ad1[0] = 1,ad2[n] = 1;
            for(int i = 1; i <= n; i++) ad1[i] = ad1[i-1] * nums[i-1];
            for(int i = n-1; i >= 0; i--) ad2[i] = ad2[i+1] * nums[i];
            for(int i = 0; i < n; i++){
                int cnt = ad1[i] * ad2[i+1];
                ans.push_back(cnt);
            }
            return ans;
        }
    };
    

    方法二:我用的是递归,虽然减少了数组空间,但增加了栈空间,但是再怎么说也是自己想出来的--

    class Solution {
    public:
        vector<int> ans;
        int N,right;
        void solve(int step,int left,vector<int>& nums){
            if(step == N-1){
                ans.push_back(left*right);
                return;
            }
            solve(step+1,left*nums[step],nums);
            right *= nums[step+1];
            ans.push_back(left*right);
        }
        vector<int> productExceptSelf(vector<int>& nums) {
            N = nums.size();
            right = 1;
            solve(0,1,nums);
            reverse(ans.begin(),ans.end());
            return ans;
        }
    };
    

    方法三:官方题解给出的空间O(1)的做法,看完竟然感觉有点...

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            vector<int> ans(n);
            ans[0] = 1;
            for (int i = 1; i < n; i++) ans[i] = ans[i-1]*nums[i-1];
            int r = 1;
            for (int i = n-1; i >= 0; i--){
                ans[i] *= r;
                r *= nums[i];
            }
            return ans;
        }
    };
    
    "没有天赋异禀,那就加倍努力"
  • 相关阅读:
    Winform dataGridView 用法
    C# 网络地址下载
    C# 位数不足补零
    python中随机生成整数
    python中time模块的调用及使用
    Windows server 2016 2019远程端口修改操作
    linux查看所有用户的定时任务 crontab
    使用Docker基于Nexus3快速搭建Maven私有仓库
    Phoenix docker 测试
    mysql锁表处理
  • 原文地址:https://www.cnblogs.com/Beic233/p/13044327.html
Copyright © 2011-2022 走看看