LeetCode-给定一个整数数组 nums 和一个整数量标值 target,请你在该数组中

分享
开发者 2024-9-12 17:58:58 69 0 来自 中国
给定一个整数数组 nums 和一个整数量标值 target,请你在该数组中找出 和为目的值 target  的那 两个 整数,并返回它们的数组下标。
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
表明:由于 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
语法

JAVA实现
class Solution {    public int[] twoSum(int[] nums, int target) {        if (nums == null)   return null;        // 哈希表key是nums values是 I        Map<Integer,Integer> map = new HashMap<>();               for (int i = 0; i < nums.length; i++) {            // 两数之和固定是nums , 另一个是target - nums[I]            int another = target - nums[I];            // 假如another也在哈希表中,且another的下标不是nums,阐明找到两数之中的别的一个数            if (map.containsKey(another) && i != map.get(another)) {                // map.get(another) 获取到别的一个数的下标                return new int[]{i, map.get(another)};            }            // 初始化哈希表             map.put(nums, i);        }                 return null;    }}LeetCode
return new int[]{map.get(another),I};
[2,7,11,15]     9
返回[0,1]
return new int[]{i,map.get(another)};
[2,7,11,15]     9
返回[1,0]
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-19 06:19, Processed in 0.141539 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表