哈希
两数之和
暴力解法
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for(let i =0;i<nums.length;i++){
let x1 = nums[i]
for(let j = 0 ; j<nums.length;j++){
if(i!=j){
let x2 = nums[j]
if(x1+x2==target){
return [i,j]
}
}
}
}
};
Map法
var twoSum = function(nums, target) {
const map = new Map()
for(let i=0;i<nums.length;i++){
let key = target-nums[i]
if(map.has(key)){
return [map.get(key),i]
}else{
map.set(nums[i],i)
}
}
return []
};
字母异味词分组
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
let map = new Map();
for (let i = 0; i < strs.length; i++) {
let word = strs[i];
// 使用数组的 sort 方法对字符串的字符进行排序,并将排序后的字符数组重新连接成字符串
let sorted_word = word.split('').sort().join('');
if (map.has(sorted_word)) {
map.get(sorted_word).push(word);
} else {
map.set(sorted_word, [word]);
}
}
// 将Map中的值(数组)转换为数组返回
return [...map.values()];
};
最长连续序列
var longestConsecutive = function(nums) {
if (nums.length === 0) return 0;
let set = new Set(nums);
let maxSize = 0;
for (let num of set) {
// 跳过非连续序列的起始数字(即那些前面有数字的数字)
if (!set.has(num - 1)) {
let currentNum = num;
let currentLength = 1;
// 遍历连续序列
while (set.has(currentNum + 1)) {
currentNum++;
currentLength++;
}
// 更新最大长度
maxSize = Math.max(maxSize, currentLength);
}
}
return maxSize;
};