1 Two Sum

作者: Mree111 | 来源:发表于2019-04-19 23:51 被阅读0次

Find two numbers in the list so the sum can match the target number.

Solution

  1. 最简单的brute force可以O(N^2)解决
    2.使用Hash Table直接做查询
class Solution {
    public int[] twoSum(int[] nums, int target) {
           Map<Integer,Integer> map = new HashMap<>();
            for(int i=0;i<nums.length;i++){
                int other=target - nums[i];
                if(map.containsKey(other))
                    return new int[] {map.get(other),i};
                
                map.put(nums[i],i);
            }
         throw new IllegalArgumentException("No two sum solution");
    }
}```

相关文章

  • LeetCode 1. Two Sum (Easy)

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

  • 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

    #1. Two Sum

  • LeetCode之Swift

    1.Two Sum (Easy)

  • X Sums

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

  • 1 two sum

    title: Two Sumtags:- two-sum- simple- hash- No.1- integer...

  • 1、Two Sum

    题设 要点 Hash表,将双重循环的O(n^2)降到O(n) 排序+首尾指针,不断移动 该题其实就是一个很简单的搜...

  • 1 Two Sum

    Given an array of integers, return indices of the two num...

  • #1 Two Sum

    最近想刷leetcode 从头开始啦这题可以用暴力方法 O(n2)的时间复杂度和哈希表O(n)的复杂度,下面贴出h...

网友评论

      本文标题:1 Two Sum

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