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;
        }
    };
    
    "没有天赋异禀,那就加倍努力"
  • 相关阅读:
    SpringBoot 整合Redis
    IDEA 修改之前保存的git地址的账号和密码
    SpringBoot 上传文件功能
    JAVA结合 JSON Web Token(JWT) 工具类
    SpringBoot 整合Spring Security框架
    Sublime Text3 设置
    Python 正则表达式
    Django+uWSGI+Nginx 部署网站
    web 设计中引入字体
    HTML 超链接返回上一级
  • 原文地址:https://www.cnblogs.com/Beic233/p/13044327.html
Copyright © 2011-2022 走看看