BM50 两数之和
function twoSum( numbers , target ) {
const ans=new Array(2)
let map=new Map();
let n=numbers.length;
for(let i=0;i<n;i++){
if(map.has(target-numbers[i])){
ans[0]=map.get(target-numbers[i])+1;
ans[1]=i+1;
break
}else{
map.set(numbers[i],i)
}
}
return ans
}
module.exports = {
twoSum : twoSum
};
BM51 数组中出现次数超过一半的数字
function MoreThanHalfNum_Solution(numbers)
{
let map=new Map(),count;
for(let i=0;i<numbers.length;i++){
count=map.get(numbers[i])||0;
map.set(numbers[i],count+1);
}
for(let i=0;i<numbers.length;i++){
if(map.get(numbers[i])>numbers.length/2){
return numbers[i];
}
}
}
module.exports = {
MoreThanHalfNum_Solution : MoreThanHalfNum_Solution
};
BM52 数组中只出现一次的两个数字
function FindNumsAppearOnce( array ) {
let set=new Set();
array=array.sort((a,b)=>(a-b))
for(let i=0;i<array.length;i++){
if(!set.has(array[i])){
set.add(array[i]);
}else{
set.delete(array[i]);
}
}
return [...set]
}
module.exports = {
FindNumsAppearOnce : FindNumsAppearOnce
};
BM53 缺失的第一个正整数
function minNumberDisappeared( nums ) {
let set = new Set();
nums.forEach(item=>set.add(item));
for(let i=1; i<=nums.length; i++){
if(!set.has(i))
return i;
}
return nums.length+1;
}
module.exports = {
minNumberDisappeared : minNumberDisappeared
};
module.exports = {
minNumberDisappeared : minNumberDisappeared
};
BM54 三数之和
var threeSum = function(nums) {
nums.sort((a, b) => {
return a - b;
})
let result = [];
for(let i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
return result;
}
if (i != 0 && nums[i] === nums[i - 1]) {
continue;
}
let left = i + 1;
let right = nums.length - 1;
while(left < right) {
let sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push([nums[i], nums[left], nums[right]]);
left++;
right--;
while(nums[left] === nums[left - 1]) {
left++;
}
while(nums[right] === nums[right + 1]) {
right--;
}
}
if (sum > 0) {
right--;
}
if(sum < 0) {
left++;
}
}
}
return result;
};
module.exports = {
threeSum : threeSum
};
|