美文网首页
leetcode1 Two Sum

leetcode1 Two Sum

作者: 叫我坤坤 | 来源:发表于2020-05-27 23:31 被阅读0次

题目

https://leetcode.com/problems/two-sum/

思路

盲猜N^2的遍历会超时,没有试。O(N)的遍历需要用到哈希表,直接用map存值和对应的下标,一次遍历即可。

代码

    // by java
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> value2index = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i ++) {
            if (value2index.get(target - nums[i]) != null) {
                int [] ret = {value2index.get(target - nums[i]), i};
                return ret;
            }
            value2index.put(nums[i], i);
        }
        return null;
    }

相关文章

  • leetcode1 two sum

    问题:Given an array of integers, returnindicesof the two nu...

  • LeetCode1:Two Sum

    注:最精华的思想是:x = nums[i] dict[x] = i取出第i个数字(以0为开头),把它的值装载...

  • leetcode1 Two Sum

    题目 https://leetcode.com/problems/two-sum/ 思路 盲猜N^2的遍历会超时,...

  • two_sum leetcode1

    题目的简介 Given an array of integers, return indices of the t...

  • X Sums

    Two Sum It is not easy to write Two-Sum right for the fir...

  • Leetcode 解题记录

    Two sum From https://leetcode.com/problems/two-sum/descri...

  • #1. Two Sum & 167 Two Sum II

    Two Sum I https://leetcode.com/problems/two-sum/#/descrip...

  • 1. Two Sum

    1. Two Sum 题目:https://leetcode.com/problems/two-sum/ 难度: ...

  • leetcode hot100

    1. Two Sum[https://leetcode-cn.com/problems/two-sum/] 字典(...

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

网友评论

      本文标题:leetcode1 Two Sum

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