Two-pointer technique

    xiaoxiao2021-03-26  31

    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:
    Remove Duplicates from Sorted ArrayTwo Sum II - Input array is sortedReverse Words in a String IIRotate ArrayValid PalindromeContainer With Most WaterProduct of Array Except Self

    转载请注明原文地址: https://ju.6miu.com/read-659902.html

    最新回复(0)