双指针
当只有一个输入, 从该输入的两端遍历
int fn(vector<int>& arr)
{
int left = 0; // left pointer index
int right = int(array.size()) - 1; // right pointer index
int ans = 0;
while(left < right)
{
if(true /* condition */)
{
// ...
left++;
}
else
{
// ...
right--;
}
}
return ans;
}
有两个输入, 两个都需要遍历
public int fn(int[] arr1, int[] arr2)
{
int i = 0; // pointer at arr1
int j = 0; // pointer at arr2
int ans = 0;
while(i < arr1.length && j < arr2.length)
{
if(true /* condition */){
// ...
i++;
}
else {
// ...
j++;
}
}
return ans;
}
滑动窗口
用指针决定运算的范围
int fn(vector<int> &arr)
{
int left = 0, right = 0, cur = 0;
while(left < right)
{
}
}
[i18n] feedback_title
[i18n] feedback_question
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.