Leetcode 1. 两数之和 java&js

js版

var twoSum = (arr, target) => {
    let map = new Map(), res = [];
    arr.forEach((item,index) => {
      const map_index = map.get(target - item);
      if(map_index !== undefined){
        res = [map_index, index]
      }else {
        map.set(item, index)
      }
    });
    return res;
  };

java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
        for(int x = 0; x < nums.length; x++) {
			      int e = nums[x];
            if(map.get(target - e) != null){
                res[0] = map.get(target - e);
                res[1] = x;
                break;
            }else {
                map.put(e, x);
            }
	     	}
        return res;
    }
}

发布了40 篇原创文章 · 获赞 12 · 访问量 860

猜你喜欢

转载自blog.csdn.net/qq_29334605/article/details/105475410