参阅基础

相关习题

LeetCode 26.删除有序数组中的重复项

题目

来源:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
难度:简单

我的题解

思路:运用快慢指针技巧。设置fast引为1,slow索引为0,快指针在前面探路,找到一个不重复的就赋值给slow并让其前进一步去准备接受下一个不重复的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let fast = 1;
let slow = 0;

while(fast < nums.length){
if(nums[fast] != nums[slow]){
slow++;
nums[slow] = nums[fast];
}
fast++
}

return slow+1;
};

Leetcode 167.两数之和

题目

来源:https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/

难度:中等

我的题解

思路:因为数组有序,所以使用双指针中的左右指针技巧(相向而行),通过调节 leftright 就可以调整 sum 的大小。直到 left >= right 结束。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
let left = 0,right = numbers.length-1;

while(left < right){
let sum = numbers[left] + numbers[right]
if(sum === target){
return [left+1,right+1];
}
else if(sum < target){
left++
}
else if(sum > target){
right--
}
}

return [-1,-1]
};

Leetcode 5.最长回文字串

题目

来源:https://leetcode.cn/problems/longest-palindromic-substring/

难度:中等

我的题解

思路:双指针相向而行。暴力解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let res = "",s1 = "",s2 =""
//遍历 s 字串的每一个字为回文串中心点
for(let i = 0;i <= s.length; i++){
// 回文串奇数情况,找到以 s[i] 为中心的回文串
s1 = palindrom(s,i,i)
// 回文串偶数情况,找到以 s[i] 和 s[i+1] 为中心的回文串
s2 = palindrom(s,i,i+1)

// 找出最长回文串
res = res.length > s1.length ? res : s1;
res = res.length > s2.length ? res : s2;
}

return res
};

// 在 s 中寻找以 s[l] 和 s[r] 为中心的最长回文串
let palindrom = function(s,l,r){
// 防止索引越界问题
// 回文串:正着念和倒着念都一样,每次while回圈字母或数字就一定得相同,不然就说明不是回文串了。
while(l >= 0 && r < s.length && s.charAt(l) == s.charAt(r)){
l--;r++;
}

return s.substring(l + 1, r)
}