1. (LeetCode) 两数之和

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

我的解法

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

很明显,两次for循环,最笨的方法,一点技巧都没有。

时间复杂度O(n2) 空间复杂度O(1)

解法1

优先降低时间复杂度 O(n2) 能不能降为O(n)呢

这里需要引入额外的存储结构来实现这个需求

思路:

  1. 先把nums怼进map中,key 为nums[x] value为下标x
  2. 再循环nums,巧用 target - nums[x] 的差值 反向查找对应的j值,这要就能取到x,j的值返回

(这里是说每种输入只有一种答案)

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

时间复杂度O(n) 空间复杂度O(n)

解法2

上面解法中两个for循环看起来也不爽,能不能降低为一个for循环呢

思路

  1. 先在map中找有没有存在的值,再put进map
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

原文地址:https://www.cnblogs.com/adroit/p/10959942.html

时间: 2024-08-29 17:56:55

1. (LeetCode) 两数之和的相关文章

LeetCode——两数之和

最近在家拧三阶魔方,把初级的玩法掌握了,也就是可以还原六个面了,速度不快,但是也很兴奋.三阶魔方的初级玩法按照套路拧就可以了,每一步需要完成的任务,该步骤转动的方法基本都是固定的,而且变化也并不是特别多.只要按照套路多练习,不考虑速度的情况下还原一个三阶魔方还是很容易的. 编程入门和还原魔方其实差不多,最初也是掌握套路后反复的练习,先从一个生手变成一个熟手,然后再去提高.分享一个段子,在知乎上看到的,如下: 陈康肃公尧咨善射,当世无双,公亦以此自矜.尝射于家圃,有卖油翁释担而立,睨之,久而不去.

leetCode:twoSum 两数之和 【JAVA实现】

LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:twoSum 两数之和 [JAVA实现] 方法一 使用双重循环两两相加判断是否等于目标值 public List<String> twoSum2(int[] arr, int sum) { if (arr == null || arr.length == 0) { return new ArrayL

[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / 3 6 / \ 2 4 7 Target = 9 Output: True Example 2: Input: 5 / 3 6 / \ 2 4 7 Targe

LeetCode 167. Two Sum II - Input array is sorted (两数之和之二 - 输入的是有序数组)

Given an array of integers that is already sorted in ascending order, 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 m

leetcode刷题--两数之和(简单)

一.序言 第一次刷leetcode的题,之前从来没有刷题然后去面试的概念,直到临近秋招,或许是秋招结束的时候才有这个意识,原来面试是需要刷题的,面试问的问题都是千篇一律的,只要刷够了题就差不多了,当然你的基础也要扎实,毕竟在技术面的时候很容易露馅的. 所以奉劝各位还未毕业,在大三或大二的师弟师妹早点刷题,心里也有底气进入求职大军,毕竟大四开始刷题的话时间上有些太紧了,推荐刷题的话就是牛客和leetcode. 回归正题,这次记录的是leetcode刷的第一题--两数之和. 二.审题 审题真的很重要

LeetCode Golang实现 1. 两数之和

1. 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元素. 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 方法一: 暴力法: leetCode 给出运行时间 60ms func twoSum(nums []int

LeetCode刷题:第一题 两数之和

从今天开始刷LeetCode 第一题:两数之和 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元素. 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 代码如下: 1 /** 2 * Note: The retur

[算法] LeetCode 1.两数之和

LeetCode 1.两数之和(python) 1.朴素解法 最朴素的两个for循环大法: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: return [i, j] 但注意,不要用enumerate函数写,会超时

LeetCode——1.两数之和

LeetCode的第一题:两数之和,给定一个整数数组nums和一个目标值target,要求在数组中找出和为目标值的两个整数,并返回它们的下标值. 代码如下: 1 var nums = [2, 7, 11, 15] 2 var target = 9 3 4 var twoSum = function (nums, target) { 5 for (let i = 0; i < nums.length; i++) { 6 for (let j = i; j < nums.length; j++)