1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.demo.s1;
import java.util.HashMap; import java.util.Map;
public class Solution {
public int[] twoSum(int[] nums, int target) { int[] ret = new int[2]; Map<Integer, Integer> cache = new HashMap<Integer, Integer>(); for(int i =0; i< nums.length; i++) { if(cache.containsKey(target -nums[i] )) { ret[0] = cache.get(target -nums[i]); ret[1] = i; break; } else { cache.put(nums[i], i); } } return ret; } public static void main(String[] args) { int[] nums = new int[]{1,2,3,4,5}; int target = 5; new Solution().twoSum(nums, target); } }
|