Array题型:双指针Two Pointers套路

一、反向

 

通用步骤:

  1. Initialize two pointer i = 0, j = array.length - 1
  2. while i <= j: 
    • Decide what you should do based on the value of array[i] and array[j]
    • Move at least one pointer forward in its direction

二、同向

Array题型:双指针Two Pointers套路_第1张图片

通用步骤:

  1. Initialize two pointers i and j, usually both equal to 0
  2. while i < array.length:
    1. if we need array[i], then we keep it by assigning array[i] = array[j], and move i forward, make it ready at the next position
    2. otherwise skip it. We do not need to move i since its spot is not fulfilled

你可能感兴趣的:(数据结构和算法,算法)