美文网首页
1、两数之和

1、两数之和

作者: 崔鹏宇 | 来源:发表于2021-03-20 21:25 被阅读0次

题目

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

你可以按任意顺序返回答案。

示例

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

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

解法一

暴力解法

第一时间就是想拿target-第一个数比较后面的数,再target-第二个数......

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

时间复杂度 为:O(N²) 由于两次for循环

空间复杂度 为:O(1)

解法二

哈希表(参考来源LeetCode官方题解)

key为target-nums[i]

value 为数组下标

如果target-nums[i]的值不在key中就去存储 如果存在就返回 本次循环的 i 和map存储的数组下标

public static int[] twoSumMap(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int num=target-nums[i];
        if (map.containsKey(num)){
            return new int[]{i,map.get(num)};
        }
        map.put(num,i);
    }
    return nums;
}

时间复杂度 为 O(N)

空间复杂度 为 O(N)

相关文章

  • 1、两数之和

    https://leetcode-cn.com/problems/two-sum/[https://leetcod...

  • 1,两数之和

    2019.5.15 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标...

  • 1 两数之和

    文|Seraph 01 | 问题 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目...

  • 1、两数之和

    题目 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数...

  • 【1】两数之和

    题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并...

  • [LeetCode] 索引

    1. 两数之和

  • leetcode top100

    1.求两数之和(数组无序) 2.求电话号码的字母组合 3.三数之和 4.两数之和(链表)

  • 【LeetCode通关全记录】1. 两数之和

    【LeetCode通关全记录】1. 两数之和 题目地址:1. 两数之和[https://leetcode-cn.c...

  • 两数之和(golang)

    原题:两数之和 关联:两数之和 II - 输入有序数组(golang)两数之和 IV - 输入 BST(golang)

  • 两数之和 II - 输入有序数组(golang)

    原题:两数之和 II - 输入有序数组 关联:两数之和(golang)两数之和 IV - 输入 BST(golan...

网友评论

      本文标题:1、两数之和

      本文链接:https://www.haomeiwen.com/subject/kfhgcltx.html