zoukankan      html  css  js  c++  java
  • leetcode| Product of Array Except Self

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

    Solve it without division and in O(n).

    For example, given [1,2,3,4], return [24,12,8,6].

    题目:题目的意思是,给出一个数组,需要你算出除了当前元素意外其他元素的乘积,这些乘积组成意外一个数组

    思路:题目对复杂度和效率是有要求的,不然直接暴力循环一遍当然也是可以实现的,这里有一个非常巧妙地做法,先贴代码后讲

    public int[] productExceptSelf(int[] nums) {

      int len  = nums.length;

      int res []  = new int[len];

      res[0] = 1;

      for(int i = 1;i<len;i++){

        res[i] = nums[i-1]*res[i-1];

      }

      int r  = 1;

      for(int i = len-1;i>=0;i--){

        res[i] *= r;     

        r  *= nums[i];

      }

      return res;

    }

    根据代码解释一下,第一个循环的作用是,将res中的i元素都赋值成i之前的元素的乘积,后一个循环是将i元素乘于i以后元素的乘积,这样一来,res[i]不就是自己以外所有其他元素的乘积了,这个算法执行时自己跟一遍,简直就有一种惊叹的感觉,太巧妙了,大家可以感受下设计的精巧之处,在老外的论坛下面都是"so clever","elegant"一片赞叹。。。。

  • 相关阅读:
    8天学通MongoDB——第三天 细说高级操作
    8天学通MongoDB——第二天 细说增删查改
    8天学通MongoDB——第一天 基础入门
    Redis Web界面管理工具
    Redis 起步
    使用 Swagger UI 与 Swashbuckle 创建 RESTful Web API 帮助文件
    面试应该如何面?
    Login oracle for external authenticate
    突然发现我脾气变好了
    一种持续构建构想
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5687269.html
Copyright © 2011-2022 走看看