问题

1.两数相加

图片.png
方式1:

  1. //如果使用暴力穷举,复杂度是n^2
  2. //使用哈希优化后是n
  3. function twoSum(nums,target){
  4. let map = new Map()
  5. nums.foreach((n,i)=>{
  6. map.add(n,i)
  7. })
  8. for(let i=0;i<nums.length;i++){
  9. const other = target-nums[i];
  10. //不能是自身
  11. if(map.get(other)&&other!==nums[i]){
  12. return[i,map.get(other)]
  13. }
  14. }
  15. return [-1,-1];
  16. }

方式2:

  1. function twoSum(nums=[]){
  2. this.map = new Set()
  3. this.nums = nums
  4. }
  5. twoSum.prototype.add = (n)=>{
  6. for(let v of this.nums){
  7. map.add(v+n)
  8. }
  9. nums.push(n)
  10. }
  11. twoSum.protoType.find = (target)=>{
  12. return this.map.has(target)
  13. }

当数组的值是有顺序时,使用双指针解