Use the double pointer technique to solve some problems in arrays and strings [Java] [leetcode] [double pointer technique]

Double pointer trick 1

The Double Pointer Technique - Scenario 1
Problem: Reverse the elements in an array.
Analysis: The idea is to swap the first element with the end, move forward to the next element, and keep swapping until it reaches the middle. We can use two pointers at the same time to complete the iteration: one starting from the first element and the other starting from the last element. Keep swapping the elements they point to until the two pointers meet.
Summary: In conclusion, one of the typical scenarios for using the double pointer trick is when you want to iterate over an array from both ends to the middle.
At this point you can use the double pointer trick: one pointer starts at the beginning and the other pointer starts at the end.
It's worth noting that this trick is often used in sorted arrays.

Reverse String (344. Reverse String)

Write a function that reverses the input string.
The input string is given as a character array char[].
Instead of allocating extra space for another array, you must modify the input array in place, using O(1)
extra space to solve this problem.
You can assume that all characters in the array are printable characters in the ASCII code table.
Example 1:
Input: ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a ","H"]

class Solution {
    
    
    public void reverseString(char[] s) {
    
    
        int head = 0;
        int tail = s.length - 1;
        char temp;
        while (head < tail) {
    
    
            temp = s[head];
            s[head] = s[tail];
            s[tail] = temp;
            head++;
            tail--;
        }
        System.out.println(Arrays.toString(s));
    }
}

Array Partition I (561. Array Partition I)

Given an array of length 2n, your task is to divide these numbers into n pairs, eg:
(a1, b1), (a2, b2), …, (an, bn) such that min(ai from 1 to n) , bi) is the largest sum.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is equal to 2, the maximum sum is 4 = min(1, 2) + min(3, 4).
Hint:
n is a positive integer in the range [1, 10000].
Elements in the array are in the range [-10000, 10000].

//分析:排序原数组然后对数组的奇数为求和并返回该值即可
//此处的排序方法选择了直接调用而非自己重写排序
class Solution {
    
    
    public int arrayPairSum(int[] nums) {
    
    
        Arrays.sort(nums);
        int sum = 0;
        for (int i = 0; i < nums.length; i += 2) {
    
    
            sum += nums[i];
        }
        return sum;
    }
}

167. Two Sum II - Input array is sorted

Given a sorted array sorted in ascending order, find two numbers such that their sum is equal to the target number.
The function should return the two subscript values ​​index1 and index2, where index1 must be less than index2.
Explanation:
The returned subscript values ​​(index1 and index2) are not zero-based.
You can assume that each input corresponds to a unique answer, and you can't reuse the same elements.
Example:
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is equal to the target number 9. So index1 = 1, index2 = 2 .

class Solution {
    
    
    public int[] twoSum(int[] numbers, int target) {
    
    
        int head = 0;
        int tail = numbers.length - 1;

        while (true) {
    
    
            int sum = numbers[head] + numbers[tail];
            if (sum == target) {
    
    
                return new int[]{
    
    head + 1, tail + 1};
            }
            if (sum > target) {
    
    
                tail--;
            } else {
    
    
                head++;
            }
        }
    }
}

Two-pointer trick 2

The Double Pointer Trick - Scenario Two
Sometimes we can use two unsynchronized pointers to solve the problem
example: given an array and a value, delete all instances of that value in place and return the new length.
**Analysis:** It's easier if we don't have space complexity constraints. We can initialize a new array to store the answers. If the element is not equal to the given target value, iterate over the original array and add the element to the new array.
In effect, it is equivalent to using two pointers, one for the iteration of the original array and the other always pointing to the last position of the new array.
Reconsider Space Constraints
Now let's reconsider the space-constrained situation.
We can employ a similar strategy, where we continue to use two pointers: one is still used for iteration, and the second always points to the next addition.
Summary:
This is a very common situation where you need to use the double pointer trick:
there is a slow pointer and a fast pointer at the same time.
The key to solving this kind of problem is
to determine the movement strategy of the two pointers.
Similar to the previous scenario, you may sometimes need to sort the array before using the double pointer trick, or you may need to use greedy thinking to decide your movement strategy.

27. Remove Element

Given an array nums and a value val, you need to remove all elements whose value is equal to val in place , and return the new length of the removed array.
Instead of using extra array space, you have to modify the input array in-place and do it with O(1) extra space.
The order of elements can be changed. You don't need to consider elements in the array beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3, the
function should return a new length of 2, and the first two elements in nums are both 2.
You don't need to consider elements in the array beyond the new length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2, the
function should return the new length 5, and the first five elements in nums are 0, 1, 3, 0, 4.
Note that these five elements can be in any order.
You don't need to consider elements in the array beyond the new length.
Explanation:
Why is the return value an integer, but the output answer is an array?
Note that the input array is passed "by reference", which means that modifications to the input array within the function are visible to the caller.
You can imagine the internal operation as follows: // nums are passed
by ** "reference" . That is, without making any copies of the arguments
int len ​​= removeElement(nums, val);
// Modifications to the input array in the function are visible to the caller.
// Based on the length returned by your function, it will print out
all elements in the array that are within that length.
for (int i = 0; i < len; i++) { print(nums[i]); }

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        if (nums.length == 0) {
    
    
            return 0;
        }
        int fast;
        int slow = 0;
        for (fast = 0; fast < nums.length; fast++) {
    
    
            if (nums[fast] != val) {
    
    
                nums[slow] = nums[fast];
                slow++;
            }
        }
        return slow;
    }
}

Max Consecutive Ones (485. Max Consecutive Ones)

Given a binary array, calculate the maximum number of consecutive 1s in it.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits and the last three digits are consecutive 1s, so the maximum number of consecutive 1s is 3.
Note:
Input The array contains only 0s and 1s.
The length of the input array is a positive integer and cannot exceed 10,000.

class Solution {
    
    
    public int findMaxConsecutiveOnes(int[] nums) {
    
    
//        新建一个数组记录连续一的个数,使用双指针技巧
        int[] record = new int[nums.length];
        int slow = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            if (nums[i] == 1) {
    
    
                record[slow] = 1;
                slow++;
            } else {
    
    
                slow = 0;
            }
        }
        //设置计数
        int count = 0;
        //便利原数组,遇到0停止,返回第一个0前的1的个数
        for (int i = 0; i < record.length; i++) {
    
    
            if (record[i] != 1) {
    
    
                break;
            } else {
    
    
                count++;
            }
        }
        return count;
    }
}

209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s , find the smallest contiguous subarray in the array that satisfies its sum ≥ s . Returns 0 if there is no matching contiguous subarray.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] is the contiguous subarray with the smallest length under the condition.
Advanced:
If you have already done the O(n) time complexity solution, try the O(n log n) time complexity solution.

class Solution {
    
    
    public int minSubArrayLen(int s, int[] nums) {
    
    
        if (nums.length == 0) {
    
    
            return 0;
        }
        if (nums[0] >= s) {
    
    
            return 1;
        }
//        当输入数组的长度大于等于二时,试着使用快慢指针计算最小的连续数组的长度
        int fast = 1;
        int slow = 0;
        int max = nums.length - 1;
        int res = max + 2;
        int sum = nums[fast] + nums[slow];
        while (fast < max) {
    
    
//            int sum = nums[fast] + nums[slow];
            while (fast < max && sum < s) {
    
    
                fast++;
                sum += nums[fast];
            }
            while (sum >= s) {
    
    
                sum -= nums[slow];
                slow++;
            }
            res = res > (fast - slow + 2) ? (fast - slow + 2) : res;
        }
        return res == max + 2 ? 0 : res;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324072857&siteId=291194637
Recommended