The beauty of discovery algorithm: collision pointer of two pointers

Time:2021-4-13

The beauty of discovery algorithm: collision pointer of two pointers

  • What is a collision pointer?

    • First knowledge
    • Algorithm diagram
    • Collision process diagram
  • Array and collision pointer in JavaScript

    • How to define collision pointer in JS?
    • Implementation of a simplest collision pointer
  • Leetcode collision pointer solution problem

    • 7. Integer inversion (easy)
    • 9. Palindrome number (easy)
    • 27. Remove element (easy)
    • 125. Verify palindrome string (easy)
    • 167. II of two – input ordered array (easy)
    • 190. Invert binary (easy)
    • 344. Reverse string (easy)
    • 345. Invert the vowels in a string (easy)
    • 11. The container with the most water (medium)

What is a collision pointer?

First knowledge

  • Collision pointer is one of the double pointer algorithms.
  • The collision pointer iterates the array from both ends to the middle. One pointer starts at the beginning and the other at the end.
  • The ending condition of the colliding pointer is that two pointers meet.
  • Collider pointers are often used to sort arrays.

Algorithm diagram

The beauty of discovery algorithm: collision pointer of two pointers

Collision process diagram

167. The collision process of II input ordered array (easy) of two numbers.
Blue pointer: head pointer red pointer: tail pointer termination condition: head tail pointer collision
The beauty of discovery algorithm: collision pointer of two pointers

Array and collision pointer in JavaScript

How to define collision pointer in JS?

name

The first and last pointers can be named as:

  • i, j
  • head, tail
  • start, end
Initial value
  • Head pointer: 0
  • Tail pointer: array length minus one
let arr = [1, 7, 5, 2];
let head = 0;
let tail = arr.length -1;

Implementation of a simplest collision pointer

The beauty of discovery algorithm: collision pointer of two pointers

var arr = new Array(10).fill(0).map((num,i)=>num+i);
var i =0;
var j = arr.length - 1;
while(i<j){
  i++;
  j--;
}
var collision = [i - 1, j + 1]
var tip = `Array's head and tail had a collision between ${collision[0]} and ${collision[1]}`;
console.log(tip); // Array's head and tail had a collision between 4 and 5

Leetcode collision pointer solution problem

  • 7. Integer inversion (easy)
  • 9. Palindrome number (easy)
  • 27. Remove element (easy)
  • 125. Verify palindrome string (easy)
  • 167. II of two – input ordered array (easy)
  • 190. Invert binary (easy)
  • 344. Reverse string (easy)
  • 345. Invert the vowels in a string (easy)
  • 11. The container with the most water (medium)

7. Integer inversion (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var reverse = function (x) {
  /**
   *Solution 2. Pointer collision method
   *Performance: 96 MS 35.38% 35.9 MB 77.35%
   */
  var sign = Math.sign(x);
  var arr = x.toString().split("");
  //
  if (sign === -1) {
    arr.shift();
  }
  //The hands collide
  var i = 0;
  var j = arr.length - 1;
  while (i < j) {
    swap(arr, i, j);
    i++;
    j--;
  }
  function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  //End of pointer collision
  var rX = parseInt(arr.join(""));
  var result = sign * rX;
  var min = -Math.pow(2, 31);
  var max = Math.pow(2, 31) - 1;
  if (rX < min || rX > max) return 0;
  return result;
};

9. Palindrome number (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var isPalindrome = function (x) {
  /**
   *Solution 3: collision pointer method
   *Performance: 244ms 45.5mb
   */
  var strArr = `${x}`.split("");
  var i = 0;
  var j = strArr.length - 1;
  while (i < j) {
    if (strArr[i] !== strArr[j]) {
      return false;
    }
    i++;
    j--;
  }
  return true;
};

27. Remove element (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var removeElement = function (nums, val) {
  /**
   *Solution 2: collision pointer
   *Performance: 64ms 33.9mb
   */
  var i = 0;
  var j = nums.length - 1;
  while (i <= j) {
    if (nums[i] === val) {
      nums.splice(i, 1);
      j--;
    } else if (nums[j] === val) {
      nums.splice(j, 1);
      j--;
    } else {
      i++;
    }
  }
  return nums.length;
};

125. Verify palindrome string (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var isPalindrome = function (s) {
  /**
   *Solution 1: regular + colliding pointer
   *Performance: 76ms 89.76% 37.5mb 70.83%
   */
  var parlinDrome = s.replace(/[^\w]/g, "").replace(/_/g, "").toLowerCase();
  var strArr = parlinDrome.split("");
  var i = 0;
  var j = strArr.length - 1;
  while (i < j) {
    if (strArr[i] !== strArr[j]) {
      return false;
    }
    i++;
    j--;
  }
  return true;
};

167. II of two – input ordered array (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var twoSum = function (numbers, target) {
  /**
   *Solution 2: collision pointer
   *Performance: 68ms 71.18% 35.2MB 76.60%
   *Time complexity: O (n ^ 2)
   */
  var left = 0;
  var right = numbers.length - 1;
  while (left < right) {
    if (numbers[left] + numbers[right] === target) {
      return [left + 1, right + 1];
    } else if (numbers[left] + numbers[right] > target) {
      right--;
    } else {
      left++;
    }
  }
};

190. Invert binary (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function (n) {
  /**
   *Solution 1: change the position of collision after rotating the array
   *Performance: 76ms 35.8mb
   *Thinking:
   *Decimal to binary: toString (2)
   *32-bit space complement 0: padstart (32,0)
   *Inversion algorithm: collision pointer method
   *Binary to decimal: parseInt (, 2)
   */
  let arr = n.toString(2).padStart(32, 0).split("");
  let head = 0;
  let tail = arr.length - 1;
  while (head < tail) {
    swap(arr, head, tail);
    head++;
    tail--;
  }
  function swap(arr, i, j) {
    let temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  let result = parseInt(arr.join(""), 2);
  return result;
};

344. Reverse string (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var reverseString = function (s) {
  /**
   *Solution 2: collision pointer
   */
  var headIdx = 0;
  var tailIdx = s.length - 1;
  while (headIdx < tailIdx) {
    swap(s, headIdx, tailIdx);
    headIdx++;
    tailIdx--;
  }
  function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  return s;
};

345. Invert the vowels in a string (easy)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function (s) {
  /**
   *Solution 1: collision pointer
   *Performance: 108 MS 31.59% 38.4 MB 66.67%
   */
  var univocalic = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
  var sArr = s.split("");
  var head = 0;
  var tail = sArr.length - 1;
  while (head < tail) {
    if (univocalic.includes(sArr[head]) && univocalic.includes(sArr[tail])) {
      swap(sArr, head, tail);
      head++;
      tail--;
    } else if (!univocalic.includes(sArr[head])) {
      head++;
    } else if (!univocalic.includes(sArr[tail])) {
      tail--;
    }
  }
  function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  return sArr.join("");
};

11. The container with the most water (medium)

Title:https://leetcode-cn.com/probl…
Explanation:https://github.com/FrankKai/l…

var maxArea = function (height) {
  /**
   *Solution 1: collision pointer method
   *Performance: 64ms 35.6mb
   * */
  var head = 0;
  var tail = height.length - 1;
  var maxCapacity = 0;
  while (head < tail) {
      maxCapacity = Math.max(Math.min(height[head], height[tail]) * (tail - head), maxCapacity)
      if (height[head] < height[tail]) {
          head++
      } else {
          tail--;
      }
  }
  return maxCapacity;
};

We are looking forward to communicating with you and making progress together. Welcome to join the technical discussion group which is closely related to front-end development

The beauty of discovery algorithm: collision pointer of two pointers

Strive to be an excellent front end engineer!

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]