Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. 思路一:两个for loop,干掉,千万别用。思路二:用map先loop一遍存起来,然后再loop一遍数组,看target-current这个差值存不存在map里。思路二优化:把两次loop合并成一次loop:
public int[] twoSum(int[] nums, int target){ int[] res = new int[2]; HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(target-nums[i])){ res[1]=map.get(target-nums[i]); res[2]=i; return res; } map.put(nums[i],i); } return res; }
时间: 2024-12-20 11:03:05