Two-pointer technique

https://leetcode.com/articles/two-pointer-technique/

I. Two-pointer technique:

One slow-runner and the other fast-runner.

One pointer starts from the beginning while the other pointer starts from the end.


 e.g. Reverse the characters in a string:


First, let's assume that we already have the swap function defined below:

private void swap(char[] str, int i, int j) {
    char temp = str[i];
    str[i] = str[j];
    str[j] = temp;
}

The idea is to swap the first character with the end, advance to the next character and swapping repeatedly until it reaches the middle position. We calculate the middle position as \lfloor\frac{n}{2}\rfloor2n. You should verify that the middle position works for both odd and even size of array.

public void reverse(char[] str) {
    int n = str.length;
    for (int i = 0; i < n / 2; i++) {
        swap(str, i, n - i - 1);
    }
}

Or we can also solve the problem using the two-pointer technique.

public void reverse(char[] str) {
    int i = 0, j = str.length - 1;
    while (i < j) {
        swap(str, i, j);
        i++;
        j--;
    }
}



Classic problems:
  1. Remove Duplicates from Sorted Array
  2. Two Sum II - Input array is sorted
  3. Reverse Words in a String II
  4. Rotate Array
  5. Valid Palindrome
  6. Container With Most Water
  7. Product of Array Except Self



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值