1. /**
    2. * @author WuQiChuan
    3. * @Description:
    4. * 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
    5. *
    6. * 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
    7. *
    8. * 示例:
    9. *
    10. * 给定 nums = [2, 7, 11, 15], target = 9
    11. *
    12. * 因为 nums[0] + nums[1] = 2 + 7 = 9
    13. * 所以返回 [0, 1]
    14. *
    15. * @Date: Created in:2018/10/17 22:56
    16. * @Version: 1.0
    17. */
    18. public class Solution {
    19. public int[] twoSum(int[] nums, int target) {
    20. Map<Integer,Integer> map = new HashMap<>();
    21. int[] res = new int[2];
    22. for (int i = 0;i<nums.length;i++){
    23. //差值等于目标减当前值
    24. int complement = target - nums[i];
    25. //如果存在和当前差值一样的key,就返回
    26. if(map.containsKey(complement)){
    27. return new int[] { map.get(complement), i };
    28. }
    29. //将数组值作为key,索引下标作为value
    30. map.put(nums[i],i);
    31. }
    32. throw new IllegalArgumentException("No two sum solution");
    33. }
    34. }