leetcode 1. 两数之和

40 阅读1分钟

Method 1 双指针,时间复杂度O(n^2)

var twoSum = function(nums, target) {
   for(let i=0;i<nums.length-1; i++){
       for(let j=i+1;j<nums.length;j++){
           if(nums[i] +nums[j] ==target){
               return [i,j];
           }
       }
   }
};

Method 2 配对,hashMap

var twoSum = function(nums, target) {
    const map = new Map();
    for(let i=0;i<nums.length;i++){
        let val = target-nums[i]
        if(map.has(val)){
            return [map.get(val),i]
        }else{
            map.set(nums[i],i);
        }
    }
};