Leetcode | Collision Pointer Algorithm Notes

The basic idea of ​​collision pointers

The basic idea of ​​colliding pointers is to use two pointers ( or , or, etc.) in data structures such as arrays or linked lists to move from different directions (usually both ends of the array) to effectively search , traverse, or judge .leftrightstartend

Common usage scenarios of collision pointers include:

  1. Searching in Sorted Arrays : Collision pointers can be used to search for a target element in a sorted array. By pointing one pointer to the beginning of the array and another pointer to the end of the array, based on the size relationship between the element pointed by the pointer and the target element, the pointer is gradually moved to the middle to achieve the purpose of quickly searching for the target element.

  2. Sum of two numbers in an ordered array : Given an ordered array and a target number, you can use the collision pointer method to find two numbers in the array so that their sum is equal to the target number. By pointing one pointer to the beginning of the array and the other to the end of the array, based on the relationship between the sum of the elements pointed to by the pointer and the target number, the pointers are gradually moved to find two numbers that meet the conditions.

  3. Palindrome string judgment : The collision pointer can be used to judge whether a string is a palindrome string. By pointing one pointer to the beginning of the string and the other to the end of the string, gradually move the pointer toward the middle, and compare whether the characters pointed to by the two pointers are equal to determine whether the string is a palindrome.

  4. Linked list operations : Use collision pointers to find the intermediate nodes of the linked list, determine whether there is a ring in the linked list, etc.

  5. ……

The advantage of colliding pointers is that it can do the job in a single pass, usually with low time complexity, and requires no extra space .

However, the premise of using colliding pointers is that the target data structure needs to meet certain conditions, such as being ordered or having specific structural properties.

Exercises related to collision pointers

Sum of Two Numbers II - Input ordered array

Question description

You are given an 1array of integers whose subscripts start from . The array has been arranged in non-decreasing order. Please find two numbers numbersfrom the array such that the sum of them is equal to the target number . targetIf these two numbers are numbers[index1]and respectively numbers[index2], then 1 <= index1 < index2 <= numbers.length.

Returns [index1, index2] the subscripted sum of these two integers as an integer array of length 2 .index1 index2

  • You can assume that each input corresponds to a unique answer, and you can't reuse the same elements.

  • The solution you design must use only a constant amount of extra space.

topic analysis and implementation

Data Structure: Array

Basic implementation method:

  • 对撞指针
Implementation 1: Collision pointers
# Use Python to solve
def two_sum(numbers, target):
    '''
    查找满足两数之和的位置
    
    参数:
    	numbers(list[int]): 非递减顺序排列的整数数组
    	target(int): 目标数
    返回值:
    	两个整数的下标    	
    '''
    
    # left指针从左往右运动
    # right指针从右往左运动
    left = 0
    right = len(numbers) - 1
    
    while left < right:
        current_sum = numbers[left] + numbers[right]
        # 如果左右指针之和大于目标数,说明right指针需要往左移动一位
        # 反之,left指针需要往右移动一位,通过这样的方式可以有效地缩小搜索空间
        if current_sum > target:
            right -= 1
        elif current_sum < target:
            left += 1
        else:            
   			 return left + 1, right + 1

Time complexity analysis:

  • Average time complexity: O ( n ) O(n)O ( n ) , where n is the length of the array. In the worst case, the left and right pointers move from both ends of the array to the middle until two numbers that meet the conditions are found or the left and right pointers meet. On average, it can be approximated that the left and right pointers meet in the middle of the array, so the entire array needs to be traversed once.
  • Best time complexity: O ( 1 ) O(1)O ( 1 ) , when the target value does not exist in the array, the array only needs to be traversed once, that is, the left and right pointers point to the first and last elements of the array respectively, and then the result is returned directly.
  • Worst time complexity: O ( n ) O(n)O ( n ) , when all elements in the array are equal to the target value, the entire array needs to be traversed, that is, the left and right pointers move from both ends to the middle until they meet.

Space complexity analysis:

  • O ( 1 ) O(1)O ( 1 ) , using a constant amount of extra space.

Verify palindrome string

Question description

If after converting all uppercase characters to lowercase and removing all non-alphanumeric characters, the phrase reads the same forwards and backwards. Then the phrase can be considered to be a palindrome string.

  • Letters and numbers are alphanumeric characters.
  • Given a string s, if it is a palindrome, return true; otherwise, return false.

topic analysis and implementation

Data Structure: Array

Basic implementation method:

  • Collision pointer
Implementation 1: Collision pointers
  1. First use the String API in Python: isalnum(), which is used to check whether all characters in the string are alphabetic and numeric characters (i.e. letters or numbers), and the return value is a Boolean value.
  2. Then, use two pointers: leftsum right( left < right ) to move from both sides to the middle to judge leftwhether rightthe sum is equal
  3. If the values ​​of both sides are not equal, it means that it is not a palindrome string, and False will be returned directly.
  4. If they are equal, take one step leftforward and rightone step back to continue judging until both parties reach the middle of the string.
# Use Python to solve
def is_palindrome(string):
    '''
    检验给定字符串中是否是回文
    参数:
        string (str): 给定字符串
    
    返回值:
        bool
    '''
    
    cleaned_string = "".join(ch.lower() for ch in string if ch.isalnum())
    
    left = 0
    right = len(cleaned_string) - 1
    # 左右指针向字符串中间进发
    while left < right:
        # 如果发现不等,直接返回False
        if cleaned_string[left] != cleaned_string[right]:
            return False
        # 若left和right的值相等,双方继续向中间进发
        left, right = left + 1, right - 1
    # 若遍历完成,说明该字符串是一个回文串
    return True

Time complexity analysis:

  • Average time complexity: O ( n ) O(n)O ( n ) , where n is the length of the string. In the average case, the string needs to be traversed once to build a new stringcleaned_stringcontaining only letters and numbers, converted to lowercase letters. Then,cleaned_stringhalf of needs to be traversed again to check whether the condition of the palindrome is met. Therefore, the time complexity is linear, i.e.O ( n ) O(n)O ( n )
  • Best time complexity: O ( 1 ) O(1)O ( 1 ) , when the string is an empty string, the result True is returned directly without any operation.
  • Worst time complexity: O ( n ) O(n)O ( n ) , when the string is a palindrome string, half of the entire string needs to be traversed, that is, the left and right pointers move from both ends to the middle.

Space complexity analysis:

  • O ( n ) O(n)O ( n ) , a new string is createdcleaned_string in which the letters and numbers from the input string are stored, converted to lowercase letters.

Reverse vowels in string

Question description

Given a string s, reverse only all vowels in the string and return the resulting string. Vowels include 'a', 'e', 'i', 'o', 'u', and may appear more than once in both uppercase and lowercase forms.

topic analysis and implementation

Data Structure: Array

Basic implementation method:

  • 对撞指针
Implementation 1: Collision pointers

We can use two pointers iii andjjj traverses the string in opposite directions.

  1. First pointer iii initially points to the stringssThe first bit of s , pointerjjj initially points to the stringssThe last position of s .
  2. In the process of traversing, we keep changing iii moves right untiliii points to a vowel
  3. At the same time, we kept putting jjj moves left untiljjj points to a vowel.
  4. At this time, if i < j i<ji<j , then we exchangeiii andjjThe vowel letter pointed by j , otherwise it means that all the vowel letters have been traversed, and you can exit the traversal process.
# Use Python to solve
def reverse_vowels(s):
    '''
    反转给定字符串中的元音字母
    
    参数:
        s (str): 一个给定字符串
    
    返回值:
        str: 完成反转后的字符串    
    '''
    char_list = list(s)
    length = len(s)
    left = 0
    right = length - 1
    vowel_list = ['a', 'e', 'i', 'o', 'u',
                  'A', 'E', 'I', 'O', 'U']
    while left < right:
        # 在每次循环迭代中,判断 char_list[left](或char_list[right) 是否为元音字母且 left 小于 right,
        # 如果不是,则将 left (或right)指针向右(或左)移动,直到找到一个元音字母。
        while char_list[left] not in vowel_list and left < right:
            left += 1
        while char_list[right] not in vowel_list and left < right:
            right -= 1
        # 找到两个元音字母后,将它们进行反转
        # 然后,将 left 指针向右移动一位,将 right 指针向左移动一位,以继续下一轮迭代。
        char_list[left], char_list[right] = char_list[right], char_list[left]
        left += 1
        right -= 1
    # 最后,使用将字符列表转换为字符串,并将其作为函数的返回值
    return "".join(char_list)

Time complexity analysis:

  • Average time complexity: O ( n ) O(n)O ( n ) , where n is the length of the string. In the worst case, the left pointerleftand right pointerrightmove from both ends of the string to the middle respectively until two vowels that meet the condition are found orleftandrightmeet. On average, it can be approximated that the left and right pointers meet in the middle of the string, so the entire string needs to be traversed once.
  • Best time complexity: O ( 1 ) O(1)O ( 1 ) , when there are no vowels in the string, the string only needs to be traversed once, that is, the left and right pointers are initially at the same position, and then the result is returned directly.
  • Worst time complexity: O ( n ) O(n)O ( n ) , when all characters in the string are vowels, the entire string needs to be traversed, that is, the left and right pointers move from both ends to the middle until they meet.

Space complexity analysis:

  • O ( n ) O(n)O ( n ) , where n is the length of the string.

The container that holds the most water

Question description

Given a length of nnn integer arrayheight heighth e i g h t . There isnnn vertical lines,iiThe two endpoints of line i are (i, 0) (i, 0)(i,0)
( i , h e i g h t [ i ] ) ( i, height[i]) (i,height[i])

Find two of the lines such that they are equal to xxThe x- axis together form a container that can hold the most water.

  • Returns the maximum amount of water the container can store.

Topic analysis and description

Data Structure: Array

Basic implementation method:

  • 对撞指针
Implementation 1: Collision pointers
# Use Python to solve
def max_area(height):
    '''
    解决最大容器问题
    
    参数:
    	height(int): 给定整数数组,表示容器的高度
    	
    返回值:
    	int:最大可容纳水量    
    '''
    # 初始化双指针和最大面积
    left = 0
    right = len(height) - 1
    max_area = 0
	
    # 两个指针向中间移动
    while left < right:
        # 比较两个指针,找到最小的那个
        # 谁小,谁移动
        if height[left] < height[right]:
           max_area = max(max_area, (right - left) * height[left])
           left += 1                
        else:
           max_area = max(max_area, (right - left) * height[right])
           right -= 1
            
    return max_area

Time complexity analysis:

  • Average time complexity: O ( n ) O(n)O ( n ) , where n is the length of the container height array. Under average circumstances, the double pointer method is used to traverse the array once, determine the minimum height of the barrel by comparing the heights pointed by the left and right pointers, and then calculate and update the current maximum area. Therefore, the time complexity is linear, i.e.O ( n ) O(n)O ( n )
  • Best time complexity: O ( 1 ) O(1)O ( 1 ) , when the height array of the container is empty or contains only one element, the result 0 is returned directly without any operation.
  • Worst time complexity: O ( n ) O(n)O ( n ) , when the container height array forms a large slope (increasing or decreasing in height), the entire array needs to be traversed once.

Space complexity analysis:

  • O ( 1 ) O(1)O ( 1 ) , using a constant amount of extra space.

Guess you like

Origin blog.csdn.net/YuvalNoah/article/details/131562895