双指针思想

双指针

Posted by HandsomeWalker on July 27, 2020

双指针

顾名思义,双指针思想解决问题的思路是利用两个指针,一前一后来遍历数组,或者一个快一个慢来遍历数组,达到降低时间复杂度的目的。典型的二分查找就是利用双指针的思想。

多用于数组或字符串查找问题,如果处理整数数组相关问题,往往需要对数组进行排序

数组问题实例-两数之和

给定一个无序的整数数组nums和一个整数target,在数组里抽取2个整数,使得这两个整数相加后的值最接近target,求这两个数

条件:nums = [4, 3, 8, 9, 3, 9, 20, -4, 8, 2],target = 6

*你只需要求一组值

function solution(nums, target) {
  const len = nums.length;
  let left = 0;
  let right = len - 1;
  const res = [];
  nums.sort((a, b) => a - b);
  let closest = nums[0] + nums[1];
  while(left < right) {
    const sum = nums[left] + nums[right];
    if (Math.abs(sum - target) < Math.abs(closest - target)) {
      closest = sum;
      res[0] = nums[left];
      res[1] = nums[right];
      if (closest === target) {
        return res;
      }
    }
    if (sum > target) {
      right--;
    } else {
      left++;
    }
  }
  return res;
}

深化

抽取3个整数

function solution(nums, target) {
  const len = nums.length;
  nums.sort((a, b) => a - b);
  let closest = nums[0] + nums[1] + nums[2];
  const res = [];
  for (let first = 0; first < len; first++) {
    let second = first + 1;
    let third = len - 1;
    while(second < third) {
      const sum = nums[first] + nums[second] + nums[third];
      if (Math.abs(sum - target) < Math.abs(closest - target)) {
        closest = sum;
        res[0] = nums[first];
        res[1] = nums[second];
        res[2] = nums[third];
        if (closest === target) {
          return res;
        }
      }
      if (sum > target) {
        third--;
      } else {
        second++;
      }
    }
  }
  return res;
}

这里看似用了3个指针,实际上只有second和third两个指针在执行核心的移动操作

字符串问题实例-字符串压缩

字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/compress-string-lcci

function solution(S) {
  const len = S.length;
  let l = 0;
  let r = 1;
  let res = '';
  while(r <= len) {
    if (S[l] !== S[r]) {
      res += S[l] + (r - l);
      l = r;
    }
    r++;
  }
  return res.length >= S.length ? S : res;
}