subsequence/subsets/subarray/substring problems

128. Longest Consecutive Sequence

hashmap, int up = nums[i], int down, int max

注:访问过的要erase

152. Maximum Product Subarray

Maximum Subarray那题的变种。由于正负得负,负负得正的关系。以A[i]结尾的max product subarray同时取决于以A[i-1]结尾的max / min product subarray以及A[i]本身。因此,对每个i,需要记录min/max product两个状态

 159. Longest Substring with At Most Two Distinct Characters

 Longest Substring with At Most K Distinct Characters

 int lengthOfLongestSubstringKDistinct(string s, int k) {
        // write your code here
        int start = 0, cnt = 0;
        int char_set[256] = {0};
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            if (char_set[s[i]]++ == 0) cnt++;
            while (cnt > k) {
                char_set[s[start]]--;
                if (char_set[s[start++]] == 0) cnt--;
            }
            ans = max(i - start + 1, ans);
        }
        return ans;
    }
187. Repeated DNA Sequences
解析:
http://blog.csdn.net/coderhuhy/article/details/43647731

构造unordered_set<string> repeated, 遍历输入的原串, 对s[i]到s[i+9]的序列构成的子串, 如未出现在repeated中, 则存入repeated;如出现在repeated中, 则说明该子串曾出现过, 符合题意要求, 将其存入答案vector<string> answer

Input: "AAAAAAAAAAAA"
Output: ["AAAAAAAAAA","AAAAAAAAAA"]
Expected: ["AAAAAAAAAA"]

-- 对于如何去重, 其一可以先收集所有答案, 再sort, unique去重, 当然这样很慢也很麻烦; 其二, 可以再构造一个unordered_set<int> check, 用于存储已经存入answer中的重复子串对应的hint值;

sort(ans.begin(), ans.end());
vector<string>::iterator end_unique = unique(ans.begin(), ans.end());
ans.erase(end_unique, ans.end());

209. Minimum Size Subarray Sum

这道题给定了我们一个数字,让我们求子数组之和大于等于给定值的最小长度,跟之前那道 Maximum Subarray 最大子数组有些类似,并且题目中要求我们实现O(n)和O(nlgn)两种解法,那么我们先来看O(n)的解法,我们需要定义两个指针left和right,分别记录子数组的左右的边界位置,然后我们让right向右移,直到子数组和大于等于给定值或者right达到数组末尾,此时我们更新最短距离,并且将left像右移一位,然后再sum中减去移去的值,然后重复上面的步骤,直到right到达末尾,且left到达临界位置,即要么到达边界,要么再往右移动,和就会小于给定值。

/////不是很懂nlog(n)

下面我们再来看看O(nlgn)的解法,这个解法要用到二分查找法,思路是,我们建立一个比原数组长一位的sums数组,其中sums[i]表示nums数组中[0, i - 1]的和,然后我们对于sums中每一个值sums[i],用二分查找法找到子数组的右边界位置,使该子数组之和大于sums[i] + s,然后我们更新最短长度的距离即可。

 
posted @ 2016-12-18 09:23  会咬人的兔子  阅读(227)  评论(0)    收藏  举报