• [LeetCode] 1. Two Sum


    Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    You can return the answer in any order.

    Example 1:

    Input: nums = [2,7,11,15], target = 9
    Output: [0,1]
    Output: Because nums[0] + nums[1] == 9, we return [0, 1].
    

    Example 2:

    Input: nums = [3,2,4], target = 6
    Output: [1,2]
    

    Example 3:

    Input: nums = [3,3], target = 6
    Output: [0,1]

    Constraints:

    • 2 <= nums.length <= 105
    • -109 <= nums[i] <= 109
    • -109 <= target <= 109
    • Only one valid answer exists.

    两数之和。

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

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

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

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

    暴力解是O(n^2)级别的复杂度,一定会超时。为了不超时,我们使用hashmap记录每个元素和他的下标。找的时候是在找 hashmap 里是否存在能组成target的另一个数字 target - nums[i]。

    LC里面有一部分题目也是需要通过hashmap或者two pointer来加快运行速度的,我总结在这个tag里了。

    时间O(n)

    空间O(n)

    JavaScript实现

     1 /**
     2  * @param {number[]} nums
     3  * @param {number} target
     4  * @return {number[]}
     5  */
     6 var twoSum = function (nums, target) {
     7     let map = {};
     8     const len = nums.length;
     9     for (let i = 0; i < len; i++) {
    10         let cur = nums[i];
    11         let complement = target - cur;
    12         if (map[complement] !== undefined) {
    13             return [map[complement], i];
    14         }
    15         map[cur] = i;
    16     }
    17 };

    Java实现

     1 class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         // corner case
     4         if (nums == null || nums.length == 0) {
     5             return new int[] {-1, -1};
     6         }
     7         // normal case
     8         HashMap<Integer, Integer> map = new HashMap<>();
     9         for (int i = 0; i < nums.length; i++) {
    10             if (map.containsKey(target - nums[i])) {
    11                 return new int[] {map.get(target - nums[i]), i};
    12             }
    13             map.put(nums[i], i);
    14         }
    15         return new int[] {-1, -1};
    16     }
    17 }

    LeetCode 题目总结

  • 相关阅读:
    使用jmeter进行性能测试-Jmeter教程及技巧汇总 (转)
    Linux防火墙(Iptables)的开启与关闭
    解决Unable to load R3 module ...VBoxDD.dll (VBoxDD):GetLastError=1790
    Linux如何修改文件/文件夹内所有文件的权限
    php抽象类的简单应用
    php接口和多态的概念以及简单应用
    关于php中数据访问的几点补充
    php中重写和final关键字的使用
    php中static静态关键字的使用
    php对象引用和析构函数的关系
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11633889.html
Copyright © 2020-2023  润新知