给定整数数组和一个目标数据,返回数组中的两数之和是目标数据的数组下标(给定结果要唯一)-leetcode

﹏ヽ暗。殇╰゛Y 2022-11-20 08:13 253阅读 0赞
  1. package com.pshdhx.easy;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. /**
  5. * twoSum
  6. * @author pshdhx
  7. * 给定 nums = [2, 7, 11, 15], target = 9
  8. 因为 nums[0] + nums[1] = 2 + 7 = 9
  9. 所以返回 [0, 1]
  10. *
  11. */
  12. public class TwoSum {
  13. /**
  14. * 暴力枚举法
  15. * @param nums
  16. * @param target
  17. * @return
  18. */
  19. public int[] twoSum(int[] nums, int target) {
  20. int res[] =new int[2];
  21. for(int i=0;i<nums.length;i++) {
  22. for(int j=i+1;j<nums.length;j++) {
  23. if(nums[i]+nums[j]==target) {
  24. res[0] = i;
  25. res[1] = j;
  26. }
  27. }
  28. }
  29. return res;
  30. }
  31. /**
  32. * 哈希法
  33. * @param nums
  34. * @param target
  35. * @return
  36. * 灵感:加法变减法=>两次循环遍历用哈希表的containsKey,数组在前,i在后;
  37. */
  38. public int[] twoSum2(int[] nums, int target) {
  39. Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
  40. for (int i = 0; i < nums.length; ++i) {
  41. if (hashtable.containsKey(target - nums[i])) {
  42. System.out.println(hashtable.get(target - nums[i])+"-----1");
  43. System.out.println(i+"-----2");
  44. return new int[]{hashtable.get(target - nums[i]), i};
  45. }
  46. hashtable.put(nums[i], i); // (2,0) (//进入判断了)
  47. System.out.println(hashtable.toString());
  48. }
  49. return new int[0];
  50. }
  51. public static void main(String[] args) {
  52. int a[]= {2, 7, 11, 15};
  53. int[] twoSum = new TwoSum().twoSum(a, 9);
  54. for(int i=0;i<twoSum.length;i++) {
  55. System.out.println(twoSum[i]);
  56. }
  57. //int[] twoSum2 = new TwoSum().twoSum2(new int[] {2, 7, 11, 15}, 9);
  58. }
  59. }

用空间换时间的做法:用哈希法减少一次遍历。

发表评论

表情:
评论列表 (有 0 条评论,253人围观)

还没有评论,来说两句吧...

相关阅读