二分
模板1
int left = 0, right = nums.size() - 1;
while(left <= right)
else if(nums[mid] < target) { left = mid + 1; }
else { right = mid - 1; }
模板2
主要用于找到当前索引和右邻居
int left = 0, right = nums.size();
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] == target){ return mid; }
else if(nums[mid] < target) { left = mid + 1; }
else { right = mid; }
if(left != nums.size() && nums[left] == target) return left;
模板3
主要用于找到左右邻居
int left = 0, right = nums.size() - 1;
while (left + 1 < right){
// Prevent (left + right) overflow
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid;
} else {
right = mid;
双指针
需要特定的数据结构维持窗口的大小
priority_queue<pair<int, int>> q;
priority_queue<int, vector, greater> large;最上面的元素是最小的元素
移动两个指针
排序
快速排序
void QuickSort(vector& nums, int l, int r)
{
if(nums.size() == 0)return;
if(l >= r)return;
int i = l, j = r;
while(i < j)
{
while(i < j && nums[j] >= nums[l]) j–;
while(i < j && nums[i] <= nums[l]) i++;
swap(nums[i], nums[j]);
}
swap(nums[i], nums[l]);
QuickSort(nums, l, i - 1);
QuickSort(nums, i + 1, r);
}
————————————————
版权声明:本文为CSDN博主「牛牛coding」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ChaseHeart/article/details/119335152
void merge_sort(vector &nums, int l, int r, vector &temp) {
if (l >= r) {
return;
}
// divide
int m = l + (r - l) / 2;
merge_sort(nums, l, m, temp);
merge_sort(nums, m+1, r, temp);
// conquer
int p = l, q = m, i = l;
while (p <= m || q < =r) {
if (q > r || (p < m && nums[p] <= nums[q])) {
temp[i++] = nums[p++];
} else {
temp[i++] = nums[q++];
}
}
for (i = l; i <= r; ++i) {
nums[i] = temp[i];
}
}