双指针的常见应用场景

1. 翻转数组的元素,之前我都是取中间值,然后ix< (right + 1 - left)/2, 这样考虑较繁琐。使用双指针,很简洁

void proc(int *arr, int left, int right) {
    for (int ix = left, jx = right; ix < jx; ix++, jx--) {
         int tmp = arr[ix]; arr[ix] = arr[jx]; arr[jx] = tmp;   
    }
}    

2. 删除数组中重复的元素

3. 对于存在环的单链表,会用到快慢指针

4. 另外,二分法和滑动窗口也都在使用双指针

 

posted @ 2025-01-01 22:46  靖意风  Views(33)  Comments(0)    收藏  举报