1. 题干描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例:

  1. 输入:nums = [2,7,11,15], target = 9
  2. 输出:[0,1]
  3. 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]

2.题解

共罗列三种解决方案,main中包含自测,点击获取源码:小骄傲的github

  1. public class TwoNumsSum {
  2. public static void main(String[] args) {
  3. int[] nums = new int[]{3,7,8,2,6,4,9};
  4. int[] result = hashMap1(nums, 6);
  5. System.out.println("result:"+ Arrays.toString(result));
  6. }
  7. //解法一:暴力搜索——时间复杂度O(n^2),空间复杂度O(1)
  8. public static int[] bruteForceSearch(int[] nums, int target){
  9. for (int i = 0; i < nums.length; i++) {
  10. for (int j = i + 1; j < nums.length; j++) {
  11. if(nums[j] == target - nums[i]) {
  12. return new int[] {i, j};
  13. }
  14. }
  15. }
  16. return new int[] {};
  17. }
  18. //解法二:哈希表版本1——时间复杂度O(n),空间复杂度O(n)
  19. public static int[] hashMap1(int[] nums,int taget){
  20. HashMap<Integer, Integer> map = new HashMap<>();
  21. int[] result = new int[2];
  22. for (int i=0;i<nums.length-1;i++){
  23. int tem = taget - nums[i];
  24. if (map.containsKey(tem)){
  25. result[0] = map.get(tem);
  26. result[1] = i;
  27. }
  28. map.put(nums[i],i);
  29. }
  30. return result;
  31. }
  32. //解法三:哈希表——时间复杂度O(n),空间复杂度O(n)
  33. public static int[] hashMap2(int[] nums,int target){
  34. int size = nums.length;
  35. Map<Integer, Integer> dic = new HashMap<>();
  36. for (int i = 0; i < size; i++) {
  37. if (dic.containsKey(target - nums[i])) {
  38. return new int[] { dic.get(target - nums[i]), i };
  39. }
  40. dic.put(nums[i], i);
  41. }
  42. return new int[0];
  43. }
  44. }