Two-pointer technique

来源:互联网 发布:淘宝买家好评率百分百 编辑:程序博客网 时间:2024/06/07 01:22

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
原创粉丝点击