您的位置:首页 > 娱乐 > 八卦 > Day07-06_13【CT】LeetCode手撕—1. 两数之和

Day07-06_13【CT】LeetCode手撕—1. 两数之和

2025/2/23 23:57:05 来源:https://blog.csdn.net/weixin_44382896/article/details/139649691  浏览:    关键词:Day07-06_13【CT】LeetCode手撕—1. 两数之和

目录

  • 题目
  • 1-思路
  • 2- 实现
    • ⭐1. 两数之和——题解思路
  • 3- ACM实现

题目

  • 原题连接:1. 两数之和

1-思路

哈希表

  • 利用哈希表存储 key 数组元素值 ——> value 数组下标
  • 遍历数组

2- 实现

⭐1. 两数之和——题解思路

在这里插入图片描述

class Solution {public int[] twoSum(int[] nums, int target) {int[] res = new int[2];// 哈希表Map<Integer,Integer> map = new HashMap<>();// 存 key 值 ——> value 下标// 遍历数组for(int i  = 0 ; i < nums.length ;i++){if(map.containsKey(target-nums[i])){res[0] = i;res[1] = map.get(target-nums[i]);}map.put(nums[i],i);}return res;}
}

3- ACM实现

public class twoSum {public static int[] twoSum(int[] nums, int target) {int[] res = new int[2];// 哈希表Map<Integer,Integer> map = new HashMap<>();// 存 key 值 ——> value 下标// 遍历数组for(int i  = 0 ; i < nums.length ;i++){if(map.containsKey(target-nums[i])){res[0] = i;res[1] = map.get(target-nums[i]);}map.put(nums[i],i);}return res;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输入数组长度");int n = sc.nextInt();int[] nums = new int[n];for(int i = 0 ; i < n;i++){nums[i] = sc.nextInt();}System.out.println("输入目标和");int target = sc.nextInt();int[] forRes = twoSum(nums,target);for(int i : forRes){System.out.print(i+" ");}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com