01.三数之和
思路:使用双指针实现。首先对数组进行升序排序,然后设第一层for循环,i从下标0的地方开始,left从i+1开始,right从数组最后一位开始。当nums[i]>0时,最外层for循环结束,返回result数组。在进行内层循环移动left和right指针时,当nums[i] + nums[left] + nums[right]>0时,说明nums[right]大了,需要将right--,反之nums[i] + nums[left] + nums[right]<0时,left++
function threeSum(nums: number[]): number[][] {
const result:number[][] = []
nums = nums.sort((a, b) => a - b)
let left = 0;
let right = nums.length - 1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] > 0) return result
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
left = i + 1
right = nums.length - 1
while (left < right) {
if (nums[i] + nums[left] + nums[right] == 0) {
result.push([nums[i], nums[left], nums[right]])
right--
left++
while (nums[right] === nums[right + 1]) {
right--;
}
while (nums[left] === nums[left - 1]) {
left++;
}
} else if (nums[i] + nums[left] + nums[right] > 0) {
right--
} else {
left++
}
}
}
return result
};
02.四数之和
思路:同三数之和
function fourSum(nums: number[], target: number): number[][] {
nums = nums.sort((a, b) => a - b)
let first = 0;
let second;
let third;
let fourth;
let result:number[][] = []
for (; first < nums.length; first++) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue
}
for (second = first + 1; second < nums.length; second++) {
if ((second - first) > 1 && nums[second] === nums[second - 1]) {
continue;
}
third = second + 1;
fourth = nums.length - 1
while (third < fourth) {
let total = nums[first] + nums[second] + nums[third] + nums[fourth]
if (total == target) {
result.push([nums[first] , nums[second] , nums[third] , nums[fourth]])
fourth--
third++
while (nums[third] === nums[third - 1]) third++;
while (nums[fourth] === nums[fourth + 1]) fourth--;
} else if (total < target) {
third++
} else {
fourth--
}
}
}
}
return result
};
03.字符串反转
思路:双指针,s[left]和s[right]的字符互换
function reverseString(s: string[]): void {
let left = 0;
let right = s.length - 1
while (left < right) {
[s[left], s[right]] = [s[right], s[left]]
left++
right--
}
};
04.反转字符串II
思路:重点在于如何遍历每段字符串的首字符
function reverseStr(s: string, k: number): string {
let sArr = s.split('')
const length = s.length - 1
const constant = 2 * k
let left,right;
for (let i = 0; i < s.length; i += constant) {
left = i;
right = (i + k - 1) > length ? length : (i + k - 1)
while (left < right) {
[sArr[left], sArr[right]] = [sArr[right], sArr[left]]
left++
right--
}
}
return sArr.join('')
};