双指针法
具体列子
1. 返回倒数第K个节点
解法:
/**
* 1. 暴力法:遍历链表,存到字符串中,读取倒数第K个节点
* 2. 快慢指针法
*/
var kthToLast = function(head, k) {
let fastNode = head
for (let i = 0; i < k; i++) {
fastNode = fastNode.next
}
let ans = head
while (fastNode) {
fastNode = fastNode.next
ans = ans.next
}
return ans.val
};
2. 验证回文字符串(LeetCode-125)
解法:
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
const normalizeS = s.replace(/\W/g, '').toLowerCase()
let start = 0
let end = normalizeS.length - 1
while (start < end) {
if (normalizeS[start] !== normalizeS[end]) return false
start++
end--
}
return true
};
3. 环形链表(LeetCode-141)
解法:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (!head) return false
let fast = head.next
let slow = head
while(fast && slow) {
if (fast === slow) return true
slow = slow.next
fast = fast.next ? fast.next.next : null
}
return false
};
4. 实现 strStr()(LeetCode-28)
解法:
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if (haystack === needle) return 0
const needleLen = needle.length
let start = 0
let end = needleLen
const len = haystack.length
if (len < needleLen) return -1
while(end <= len) {
if (haystack.slice(start, end) === needle) return start
start++
end++
}
return -1
};
5. 反转字符串中的元音字母(LeetCode-345)
解法:
/**
* @param {string} s
* @return {string}
*/
var reverseVowels = function (s) {
s = s.split("");
let u = new Set("aeiouAEIOU".split(""));
let l = 0, r = s.length - 1;
while (true) {
while (l < r && l < s.length && r >= 0 && !u.has(s[l])) l++;
while (l < r && l < s.length && r >= 0 && !u.has(s[r])) r--;
if (l >= r) {
break;
}
let t = s[l];
s[l] = s[r];
s[r] = t;
l++;
r--;
}
return s.join("");
};
6. 移动零(LeetCode-283)
解法:
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
const len = nums.length;
let start = 0
for (let i = 0; i < len; i++) {
if (nums[i] !== 0) {
[nums[start], nums[i]] = [nums[i], nums[start]]
start++
}
}
};
7. 合并两个有序数组(LeetCode-88)
解法:
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
if (!n) return
let count = m + n - 1
let l1 = m > 1 ? m - 1 : 0
let l2 = n > 1 ? n - 1 : 0
while (l1 >= 0 && l2 >= 0) {
nums1[count--] = nums1[l1] < nums2[l2] ? nums2[l2--] : nums1[l1--]
}
if (l2 >= 0) {
for (let i = 0; i <= l2; i++) {
nums1[i] = nums2[i]
}
}
};