[leetcode] 238. Product of Array Except Self (medium)

版权声明:by ruohua3kou https://blog.csdn.net/ruohua3kou/article/details/82835831

原题

思路:
注意时间复杂度,分别乘积左右两边,可达到O(n)

class Solution {
 public:
  vector<int> productExceptSelf(vector<int> &nums) {
    int len = nums.size();
    vector<int> res(len, 1);
    int left = 1, right = 1;
    for (int j = 1; j < len; j++) {
      left *= nums[j - 1];
      res[j] *= left;
    }

    for (int i = len - 2; i >= 0; i--) {
      right *= nums[i + 1];
      res[i] *= right;
    }
    return res;
  }
};

猜你喜欢

转载自blog.csdn.net/ruohua3kou/article/details/82835831
今日推荐