前端算法打卡

103 阅读1分钟

1.两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/tw…

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
 var twoSum = function(nums, target) {
  var res = [];
  for(var i=0;i<nums.length;i++) {
    var tmp = target-nums[i];
    if(res[tmp] !== undefined){
      return [res[tmp], i];
    }
    res[nums[i]] = i;
  }
};

2.三数之和

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/3s…

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    const res = [],n=nums.length;
    let head,end,fixVal;
    nums.sort((a,b)=>a-b);
    if(nums.length<3 || nums[0]>0 || nums[n-1]<0) return res;
    if(!nums[0] && !nums[n-1]) return [[0,0,0]];
    for(let i=0;i<n;i++){
       fixVal = nums[i];
       if(fixVal === nums[i-1]) continue;
       if(fixVal > 0) break;
       head = i+1;
       end = n-1;
       while(head<end){
           const target = nums[head]+nums[end]+fixVal;
           if(target===0){
               res.push([nums[head],nums[end],fixVal]);
               head +=1;
               end -=1;
               while(head<end && nums[head]===nums[head-1]){
                  head += 1;
               }
               while(head<end && nums[end]===nums[end+1]){
                  end -= 1;
               }
           } else if(target<0){
                head++;
           } else {
               end--;
           }
       }
    }

    return res;
};