doukuangxun5382 2018-03-22 11:28
浏览 36

为什么我的LeetCode的“增加子序列TLE”的Golang代码?

The problem is on LeetCode:

  1. Increasing Subsequences

Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2.

Example:

Input: [4, 6, 7, 7]

Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

I have wrote the same algorithm in C++ and Golang respectively.

The Golang version keeps getting TLE on the case [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]. But the C++ version worked well and beat 72% cpp solutions.

I had a hard time trying to find out what's wrong with the Golang version, so I really appreciate your help.

Here are my codes:

Golang:

func findSubsequences(nums []int) [][]int {

    n := len(nums)
    m := make(map[int]int)
    cur := make([][]int, 1)
    cur[0] = []int{}

    var ans [][]int
    for i := 0; i < n; i++ {
        lim := len(cur)

        st, ok := m[nums[i]]
        if !ok {
            st = 0
        }

        m[nums[i]] = lim

        for j := st; j < lim; j++ {
            if len(cur[j]) > 0 && nums[i] < cur[j][len(cur[j])-1] {
                continue
            }

            tmp := append(cur[j], nums[i])
            cur = append(cur, tmp)

            if len(tmp) >= 2 {
                ans = append(ans, tmp)
            }
        }
    }

    return ans
}

C++:

class Solution {
public:
    vector<vector<int>> findSubsequences(vector<int>& nums) {
        vector<vector<int>> ans, cur;
        cur.push_back(vector<int>());

        unordered_map<int, int> m;

        int n = nums.size(), st;
        for (int i = 0; i < n; ++i) {
            if (m.count(nums[i]))
                st = m[nums[i]];
            else 
                st = 0;

            int lim = cur.size();
            m[nums[i]] = lim;
            for (int j = st; j < lim; j++) {
                if (cur[j].size() > 0 && nums[i] < cur[j].back())
                    continue;

                cur.push_back(cur[j]);
                cur.back().push_back(nums[i]);

                if (cur.back().size() >= 2)
                    ans.push_back(cur.back());
            }
        }

        return ans;
    }
};
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看