LeetCode 1. 两数之和

    技术2022-07-10  101

    目录结构

    1.题目

    2.题解

    2.1暴力法

    2.2哈希表


    1.题目

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

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

    示例:

    给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

     

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    2.题解

    2.1暴力法

    两层循环,每个元素都与后面的元素比较,满足条件则返回数组下标。

    public class Solution1 { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; int len = nums.length; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; } } } return result; } } 时间复杂度:空间复杂度:

    2.2哈希表

    在进行迭代并将元素插入到表中的同时,回过头来检查表中是否已经存在当前元素所对应的目标元素。

    如果它存在,则已经找到了对应解,并将其下标返回。

    public class Solution1 { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { return new int[]{map.get(target - nums[i]), i}; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } } 时间复杂度:空间复杂度:​​​​​​​
    Processed: 0.012, SQL: 9