Two Sum

1|0**Two Sum **

题目描述:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where
index1 must be less than index2. Please note that your returned answers (both index1 and index2) are
not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
翻译后的大致意思是:
从给定的数组中找两个元素,使得 两个元素的值满足 所给的要求 target,注意:输出的不是下标,而是元素的位置(或者说是第几个元素)

具体的方法有三种:

  1. 暴力法,复杂度为O(n2),会超时
  2. 使用一个哈希表,存储元素及其下标,复杂度为O(n)
  3. 先排序,然后左右夹逼,排序O(nlogn),左右夹逼O(n),最终O(nlogn),但是这是返回数子本身并不是返回下标,这题要返回的是下标
public class Solution04 { public int[] twoSum(int[] nums, int target) { // 定义一个hash表来存储每个数和对应的下标 final HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { // 注意 (K,V) 的位置 // 起初我就是把key和value定义反了导致查找 target - value 时不能找到 index map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { // 获取 target - num[i] 也就是 target - value 的值的对应的index final Integer v = map.get(target - nums[i]); // 判断对应的 index 是否存在且大于当前的下标 if (v != null && v > i) { return new int[]{i + 1, v + 1}; } } // 不存在返回 null return null; } } class Main04 { public static void main(String[] args) { Solution04 solution04 = new Solution04(); int[] nums = {2, 7, 11, 15}; int target = 9; int[] ints = solution04.twoSum(nums, target); System.out.println(Arrays.toString(ints)); } }

__EOF__

本文作者K35
本文链接https://www.cnblogs.com/kingmc/p/16955039.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   KksS-  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示