跳过正文
  1. Posts/

leetcode 238. Product of Array Except Self (乱搞)

·1 分钟

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].

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

 先来个O(n)空间的无脑解法。。。一个前缀积一个后缀积就好了。。。

 1class Solution {
 2public:
 3    vector<int> productExceptSelf(vector<int>& nums) {
 4        vector<int>res;
 5        vector<int>pre,suf;
 6        int siz = nums.size();
 7        if (siz==0) return res;
 8        for ( int i = 0 ; i < siz ; i++)
 9        {
10            int tmp;
11            if (i==0) tmp = nums[0];
12            else tmp = pre[i-1]*nums[i];
13            pre.push_back(tmp);
14        }
15        int cnt = 0 ;
16        for ( int i = siz -1 ; i>= 0 ; i--)
17        {
18            int tmp;
19            if (i==siz-1) tmp = nums[siz-1];
20            else tmp = suf[cnt++]*nums[i];
21            suf.push_back(tmp);
22        }
23      //  for ( int i = 0 ; i < siz ; i++) printf("%d ",pre[i]); puts("");
24    //    for ( int i = 0 ; i < siz ; i++) printf("%d ",suf[i]);puts("");
25        reverse(suf.begin(),suf.end());
26        for ( int i = 0 ; i < siz;  i++)
27        {
28            int l = i-1;
29            int r = i+1;
30            int x,y;
31            if (l<0) x = 1;
32            else x = pre[l];
33            if (r>=siz) y = 1;
34            else y = suf[r];
35      //      cout<<"x:"<<x<<" y:"<<y<<endl;
36            res.push_back(x*y);
37        }
38        return res;
39
40    }
41};

常数空间的做法。。。想了半天没有想法。。。

看了solution…发现就是借用res数组搞事情。。。。每个位置的答案扫完两遍得到。。。

感觉。。。非常的。。。无聊啊。。。。真心没意思吧,还以为是什么巧妙的做法呢。。。

相关文章

leetcode 79. Word Search (dfs)

·1 分钟
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

leetcode 289. Game of Life (模拟)

·3 分钟
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.” Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):