两数之和

两数之和

题目链接

leetcode

题目描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

示例 1:

输入:

nums = [2,7,11,15], target = 9

输出:

[0,1]

解释:

因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:

nums = [3,2,4], target = 6

输出:

[1,2]

示例 3:

输入:

nums = [3,3], target = 6

输出:

[0,1]

题目解法

第一种:暴力循环 时间复杂度为O(MN)

直接双重for循环,一个个比较

    public static int[] twoSum(int[] nums, int target) {
        int[] indexs = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = 1 + i; i < nums.length; i++) {
                if (target == nums[i] + nums[j]) {
                    indexs[0] = i;
                    indexs[1] = j;
                }
            }
        }
        return indexs;
    }

第二种:hash表 时间复杂度为O(1)

用hash表来查找,第一次进来,用目标数减去第一个数,得到的结果,当做key存到hash里面,value用来记录当前数组中值的索引,循环第二次,先去判断hash里面包含有需要查找的差值(key),
如果有,就记录当前元素所在的索引位置,再用当前元素作为key,去hash中取另外一个元素的索引,
如果没有,就继续用目标数减去当前元素,得到的结果当做key存到hash里,value用来记录当前数组中值的索引
以此循环

public static int[] twoSum(int[] nums, int target) {
        int[] arr = new int[2];
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i = 0; i<nums.length;i++) {
            if(map.containsKey(nums[i])) {
                arr[0] = i;
                arr[1] = map.get(nums[i]);
                return arr;
            }
            map.put(target-nums[i],i);
        }
        return arr;
    }
posted @   China熊孩子  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示