【LeetCode】双指针 two_pointers(共47题)
【3】Longest Substring Without Repeating Characters
【11】Container With Most Water
【15】3Sum (2019年2月26日)
给了一个乱序的数组,返回一个结果数组,数组里面每个元素是一个三元组, 三元组的和加起来为0。
题解:先固定第一个数,然后后面两个数的控制用夹逼定理,2 pointers 来解。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
const int n = nums.size();
vector<vector<int>> res;
if (nums.size() < ) {return res;}
sort(nums.begin(), nums.end());
for (int i = ; i < n; ) {
int left = i + , right = n - ;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == ) {
res.push_back(vector<int>{nums[i], nums[left], nums[right]});
++left, --right;
while (left < right && nums[left] == nums[left-]) { ++left; }
while (left < right && nums[right] == nums[right+]) { --right; }
} else if (sum < ) {
++left;
while (left < right && nums[left] == nums[left-]) { ++left; }
} else {
--right;
while (left < right && nums[right] == nums[right+]) { --right; }
}
}
++i;
while (i < n && nums[i] == nums[i-]) {++i;}
}
return res;
}
};
【16】3Sum Closest (2019年2月26日)
【18】4Sum ()
【19】Remove Nth Node From End of List
【26】Remove Duplicates from Sorted Array
【27】Remove Element
【28】Implement strStr()
【30】Substring with Concatenation of All Words
【42】Trapping Rain Water
【61】Rotate List
【75】Sort Colors
【76】Minimum Window Substring (2019年1月13日,算法群,第一次写,需要复习)
给了两个字符串 S 和 T, 在S中求一个最短子串,这个字串需要包含 T 中的所有字母。
题解: sliding window, (有两种,窗口大小可变和窗口大小不变的)。用 2 pointers 模拟窗口。时间复杂度是 O(N)。用一个 hash-map mp 记录 t 中的字母频次。用一个 count 变量记录已经满足了的 字母数量。当 mp.size() == count 的时候就可以考虑缩小窗口。https://www.youtube.com/watch?v=9qFR2WQGqkU
class Solution {
public:
string minWindow(string s, string t) {
const int ssize = s.size(), tsize = t.size();
if (ssize < tsize) {
return "";
}
unordered_map<char, int> mp;
for (auto c : t) {
mp[c]++;
}
int slow = , fast = , minLen = INT_MAX, start = , count = ;
for (; fast < ssize; ++fast) {
char c = s[fast];
if (mp.find(c) == mp.end()) {
continue;
}
mp[c]--;
if (mp[c] == ) { count++; }
while (count == mp.size()) {
if (fast - slow + < minLen) {
minLen = fast - slow + ;
start = slow;
}
char c1 = s[slow++];
if (mp.find(c1) == mp.end()) { continue; }
mp[c1]++;
if (mp[c1] == ) {
count--;
}
}
}
return minLen == INT_MAX ? "" : s.substr(start, minLen);
}
};
【80】Remove Duplicates from Sorted Array II
【86】Partition List
【88】Merge Sorted Array
【125】Valid Palindrome
【141】Linked List Cycle
【142】Linked List Cycle II
【159】Longest Substring with At Most Two Distinct Characters
【167】Two Sum II - Input array is sorted
【209】Minimum Size Subarray Sum (2019年1月11日,算法群)
给了 n 个正整数 nums 数组,和一个正整数 s,要求返回一个最短连续子数组的长度,使得这个子数组的和大于等于s。
follow-up 是 如果想出了 O(n) 的做法,能不能想出 O(nlogn) 的做法。
题解:O(N) 的做法是 2 pointers, O(nlogn) 的做法是 前缀和 + 二分
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
const int n = nums.size();
int p1 = , p2 = ;
int ans = n + , cur_sum = ;
while (p1 <= p2 && p2 < n) {
cur_sum += nums[p2];
while (p1 < p2 && cur_sum - nums[p1] >= s) {
cur_sum -= nums[p1];
++p1;
}
if (cur_sum >= s) {
ans = min(p2 - p1 + , ans);
}
++p2;
}
return ans == n + ? : ans;
}
};
【234】Palindrome Linked List
【259】3Sum Smaller (2019年2月26日,谷歌 tag)
给了一个乱序的数组,能不能从中找出三个数,nums[i], nums[j], nums[k] 他们三个想加的和小于target,返回这样三个数的个数。要求时间复杂度是O(N^2)
题解:我想出来的 O(n^2) 的解法是用个map辅助,实时更新map。但是这题的标准解法是先sort,然后先选出一个数,然后剩下两个数用夹逼定理。
class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
const int n = nums.size();
sort(nums.begin(), nums.end());
int res();
for (int i = ; i < n; ++i) {
res += twoSumSmaller(nums, i + , target - nums[i]);
}
return res;
}
int twoSumSmaller(vector<int>& nums, int start, int target) {
int left = start, right = nums.size() - ;
int res();
while (left < right) {
int sum = nums[left] + nums[right];
if (sum < target) {
res += right - left; //包含nums[left]的所有可能解
++left;
} else {
--right;
}
}
return res;
}
};
【283】Move Zeroes
【287】Find the Duplicate Number
【344】Reverse String (2018年12月3日,第一次review,ko)
逆序一个字符串。
题解:见string分类:https://www.cnblogs.com/zhangwanying/p/9885334.html
【345】Reverse Vowels of a String (2018年12月4日,第一次review,ko)
逆序一个字符串的元音字母。
题解:见string分类:https://www.cnblogs.com/zhangwanying/p/9885334.html
【349】Intersection of Two Arrays (2018年11月6日,算法群相关题)
hash-table 里面有这题,我就不重复写了。hash-table:https://www.cnblogs.com/zhangwanying/p/9886262.html
【350】Intersection of Two Arrays II (2018年11月6日,算法群)
hash-table 里面有这题,我就不重复写了。hash-table:https://www.cnblogs.com/zhangwanying/p/9886262.html
【360】Sort Transformed Array
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Note:Both the string's length and k will not exceed 10^4.
Example 1:
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input:
s = "AABABBA", k = 1
Output:
4
Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
题解:标准sliding window。但是那个cnt的意义有所不同,这里的cnt叫做 maxRepeat ,代表的意义有所不同。注意体会思路。
class Solution {
public:
int characterReplacement(string s, int k) {
const int n = s.size();
if (n == ) {return ;}
int start = , end = , maxRepeat = ;
int res = ;
unordered_map<char, int> mp;
for (; end < n; ++end) {
char c = s[end];
mp[c]++;
maxRepeat = max(mp[c], maxRepeat);
while (end - start + - maxRepeat > k) {
char t = s[start];
mp[t]--; ++start;
for (auto& p : mp) {
maxRepeat = max(maxRepeat, p.second);
}
}
res = max(end - start + , res);
}
return res;
}
};
判断一个循环数组是不是里面是不是含有环,circular array.
If a number k at an index is positive, then move forward k steps. Conversely, if it’s negative (-k), move backward k steps. Since the array is circular, you may assume that the last element’s next element is the first element, and the first element’s previous element is the last element.
Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same index and the cycle’s length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.
Could you solve it in O(n) time complexity and O(1) extra space complexity?
题解:快慢指针。这个题目只能沿着一个方向走,所以我们需要判断一下,当前的方向是不是一开始的方向相同,也就是快指针每走一步都要判断一下出发点的数字是不是相同的符号,也就是while循环的部分。
当快慢指针相遇的时候,需要判断一下环的大小是不是1个结点,如果是的话这样是。如果大于一个结点,则返回true。
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
const int n = nums.size();
for (int i = ; i < nums.size(); ++i) {
if (!nums[i]) {continue;}
int slow = i, fast = i;
while (nums[fast] * nums[i] > && nums[getNext(fast, nums)] * nums[i] > ) {
slow = getNext(slow, nums), fast = getNext(getNext(fast, nums), nums);
if (slow == fast) {
if (getNext(slow, nums) != slow) { return true; }
else {break;}
}
}
/*
//把走过的slow set成为不能走的状态
slow = i;
while (nums[slow] * nums[i] > 0) {
nums[slow] = 0;
slow = getNext(slow, nums);
}
*/
}
return false;
}
int getNext(int cur, vector<int>& nums) {
const int n = nums.size();
int res = (nums[cur] + cur) % n;
return res < ? res + n : res;
}
};
【487】Max Consecutive Ones II (2018年11月27日)(2019年3月3日更新)
给了一个0/1数组,问如果最多只能把一个 0 变成 1 的话,那么这个数组里面最长的连续 1 有几个?
题解:我是对于每一个 0 都求出了它前面连续 1 的个数 和后面连续 1 的个数。然后再遍历一边原数组,求长度,比较。注意如果全 1 的情况需要考虑。
discuss里面有更好的解法,不用多两个数组。
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
const int n = nums.size();
vector<int> pre(n, -), next(n, -);
int cnt = ;
for (int i = ; i < n; ++i) {
if (nums[i] == ) {
pre[i] = cnt;
cnt = ;
} else {
cnt++;
}
}
cnt = ;
for (int i = n-; i >= ; --i) {
if (nums[i] == ) {
next[i] = cnt;
cnt = ;
} else {
cnt++;
}
}
int ret = ;
cnt = ;
for (int i = ; i < n; ++i) {
if (nums[i] == ) {
ret = max(ret, pre[i] + next[i] + );
cnt = ;
} else {
cnt++;
ret = max(cnt, ret);
}
}
return ret;
}
};
follow-up:What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
2019年3月3日更新,这题和 1004 这周周赛题一模一样,这个是最多能变一个1,1004是是最多能变 k 个 1。解法是 sliding window with 2 pointers。
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
const int n = nums.size();
int start = , cnt = , res = ;
for (int i = ; i < n; ++i) {
if (nums[i] == ) {cnt++;}
while (cnt > ) {
if (nums[start] == ) {--cnt;}
++start;
}
res = max(res, i - start + );
}
return res;
}
};
【524】Longest Word in Dictionary through Deleting
【532】K-diff Pairs in an Array
【567】Permutation in String
【632】Smallest Range
【713】Subarray Product Less Than K (2019年2月11日)
给了一个数组,返回有多少子数组的乘积小于K。
题解:暴力解法O(N^2),2 pointers + sliding window 可以优化到 O(N). 每一步都往移动一个end指针,如果当前的乘积大于等于k了,就往前移动begin指针。计算包含当前end的子数组个数。
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
const int n = nums.size();
int begin = , end = , multi = , res = ;
while (end < n) {
multi = multi * nums[end];
while (begin < end && multi >= k) {
multi /= nums[begin];
++begin;
}
if (multi < k) {
res += (end - begin + );
}
++end;
}
return res;
}
};
【723】Candy Crush
【763】Partition Labels
【826】Most Profit Assigning Work
【828】Unique Letter String (H)(2019年3月5日)
A character is unique in string S
if it occurs exactly once in it.
For example, in string S = "LETTER"
, the only unique characters are "L"
and "R"
.
Let's define UNIQ(S)
as the number of unique characters in string S
.
For example, UNIQ("LETTER") = 2
.
Given a string S
with only uppercases, calculate the sum of UNIQ(substring)
over all non-empty substrings of S
.
If there are two or more equal substrings at different positions in S
, we consider them different.
Since the answer can be very large, return the answer modulo 10 ^ 9 + 7
.
Example 1:
Input: "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Evey substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 Example 2:
Input: "ABA"
Output: 8
Explanation: The same as example 1, except uni("ABA") = 1. Note: 0 <= S.length <= 10000.
题解:hanson solution:https://leetcode.com/problems/unique-letter-string/discuss/
class Solution {
public:
const int mod = 1e9+;
int uniqueLetterString(string S) {
vector<vector<int>> dp(, vector<int>(, -));
int res = ;
const int n = S.size();
for (int i = ; i < n; ++i) {
int idx = S[i] - 'A';
res = (res + (dp[idx][] - dp[idx][]) * (i - dp[idx][])) % mod;
dp[idx][] = dp[idx][];
dp[idx][] = i;
}
for (int i = ; i < ; ++i) {
res = (res + (dp[i][] - dp[i][]) * (n - dp[i][])) % mod;
}
return res;
}
};
【838】Push Dominoes
【844】Backspace String Compare
【845】Longest Mountain in Array
【881】Boats to Save People
【LeetCode】双指针 two_pointers(共47题)的更多相关文章
- Leetcode 简略题解 - 共567题
Leetcode 简略题解 - 共567题 写在开头:我作为一个老实人,一向非常反感骗赞.收智商税两种行为.前几天看到不止两三位用户说自己辛苦写了干货,结果收藏数是点赞数的三倍有余,感觉自己的 ...
- 剑指offer 面试47题
面试47题:题:礼物的最大价值 题目:在一个mxn的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于0),你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格,直到到达棋盘的 ...
- LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
- 【LeetCode】堆 heap(共31题)
链接:https://leetcode.com/tag/heap/ [23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无 ...
- 【LeetCode】排序 sort(共20题)
链接:https://leetcode.com/tag/sort/ [56]Merge Intervals (2019年1月26日,谷歌tag复习) 合并区间 Input: [[1,3],[2,6], ...
- 【LeetCode】动态规划(下篇共39题)
[600] Non-negative Integers without Consecutive Ones [629] K Inverse Pairs Array [638] Shopping Offe ...
- 【LeetCode】二叉查找树 binary search tree(共14题)
链接:https://leetcode.com/tag/binary-search-tree/ [220]Contains Duplicate III (2019年4月20日) (好题) Given ...
- 【LeetCode】数学(共106题)
[2]Add Two Numbers (2018年12月23日,review) 链表的高精度加法. 题解:链表专题:https://www.cnblogs.com/zhangwanying/p/979 ...
- 【LeetCode】位运算 bit manipulation(共32题)
[78]Subsets 给了一个 distinct 的数组,返回它所有的子集. Example: Input: nums = [,,] Output: [ [], [], [], [,,], [,], ...
随机推荐
- python学习笔记(九)内置函数
print(all([1,2,3,4]))#判断可迭代的对象里面的值是否都为真 True print(any([0,1,2,3,4]))#判断可迭代的对象里面的值是否有一个为真 True print( ...
- VS2017 IDE 说明
- php中ajax的使用实例讲解
一.总结 1.多复习:代码都挺简单的,就是需要复习,要多看 2.ajax原理:ajax就是部分更新页面,其实还在的html页面监听到事件后,然后传给服务器进行操作,这里用的是get方式来传值到服务器, ...
- KindEditor 完全复制word内容
Chrome+IE默认支持粘贴剪切板中的图片,但是我要发布的文章存在word里面,图片多达数十张,我总不能一张一张复制吧?Chrome高版本提供了可以将单张图片转换在BASE64字符串的功能.但是无法 ...
- prim 模板
#include<cstdio> #include<vector> #include<cstring> #include<set> #define ma ...
- 打印XX提交的svn版本信息
打印出匹配uliuchao或--结尾的行 svn log | sed -n '/uliuchao/,/--$/p'
- php面试专题---10、网络协议考点
php面试专题---10.网络协议考点 一.总结 一句话总结: 网络的考点其实就是这些:常见状态码,常见协议,osi七层模型,http和https 1.HTTP/1.1中,状态码200.301.304 ...
- 42 Bing Search Engine Hacks
42 Bing Search Engine Hacks November 13, 2010 By Ivan Remember Bing, the search engine Microsoft lau ...
- oracle、sql developer 删除某用户下所有的表
1.在sql developer内 select 'drop table "'||table_name||'";' from cat where table_type= ...
- ubuntu 16.4下hadoop配置伪分布式时出现的坑
在ubuntu16.4下spark的单机/伪分布式配置我在此就不在一一赘述,详情请点击如下连接: Hadoop安装教程_单机/伪分布式配置_Hadoop2.6.0/Ubuntu14.04 我出现问题是 ...