实现原理一样,时间复杂度O(n)
JavaScript实现
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let tempMap= new Map() for(let i = 0; i < nums.length; i++){ let numOther = target - nums[i] if (tempMap.has(numOther)) { return [tempMap.get(numOther), i] } tempMap.set(nums[i], i) } };
Java实现
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> tempMap = new HashMap<>(); for(int i=0; i<nums.length;i++){ int numOther = target - nums[i]; if(tempMap.containsKey(numOther)){ return new int[] {tempMap.get(target- nums[i]), i}; } tempMap.put(nums[i], i); } throw new IllegalArgumentException("none") ; } }
力扣----1.两数之和(JavaScript, Java实现)
原文:https://www.cnblogs.com/manru75/p/12920242.html