Java 二和三-数据结构设计

Java 二和三-数据结构设计,java,Java,我的解决方案因超过时间限制而失败。如何改进以下leetcode问题的解决方案 设计并实现一个TwoSum类。它应该支持以下操作:添加和查找 添加-将数字添加到内部数据结构中。 查找-查找是否存在总和等于该值的任何一对数字 例1: add(1); add(3); add(5); find(4) -> true find(7) -> false 代码: class TwoSum{ Set nums=new HashSet(); Set res=新的HashSet(); /**在这里初

我的解决方案因超过时间限制而失败。如何改进以下leetcode问题的解决方案

设计并实现一个TwoSum类。它应该支持以下操作:添加和查找

添加-将数字添加到内部数据结构中。 查找-查找是否存在总和等于该值的任何一对数字

例1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false
代码:

class TwoSum{
Set nums=new HashSet();
Set res=新的HashSet();
/**在这里初始化数据结构*/
公帑{
}
/**将数字添加到内部数据结构中*/
公共无效添加(整数){
用于(整数s:nums)
{
res.add(s+编号);
}
增加(数字);
}
/**查找是否存在总和等于该值的任何一对数字*/
公共布尔查找(int值){
if(res.contains(value))
返回true;
其他的
返回false;
}
}
/**
*您的TwoSum对象将按如下方式实例化和调用:
*TwoSum obj=新TwoSum();
*对象添加(编号);
*布尔参数2=对象查找(值);
*/

您当前的方法将尝试向
res
集合添加O(n2)值

说明:

当添加第一个数字时,向
res
添加0个值。 当添加第二个数字时,将向
res
添加1个值。 当添加第三个数字时,向
res
添加两个值。 ... 当添加第n个数字时,将n-1个值添加到
res

这将为您提供0+1+2+…+n-1=O(n2),当
n
较大时效率较低

你可以尝试另一种方法。消除
res
设置
。将输入的数字存储在一个
哈希集中

Set nums=new HashSet();
这使得添加变得微不足道。只需执行
nums.add(number)
,这需要
O(1)
时间

现在,对于
find
,迭代
Set
的元素,对于每个元素
x
,检查
nums.是否包含(vaule-x)&&(value-x!=x)
。如果发现这样的
x
,则返回true。这将花费
O(n)
时间


第二个条件
(value-x!=x)
将防止误报。但是,如果相同的数字可以加两次,则可能会导致误报。要支持重复的数字,您必须为添加两次的数字存储额外的数据。

这是我在Golang中使用哈希映射的解决方案。加法的空间复杂度为O(n),查找的时间复杂度为O(n)

type TwoSum struct {
    data map[int]struct{}
}

func New() *TwoSum {
    return &TwoSum{
        data: make(map[int]struct{}),
    }
}

// Add the number to the internal data structure.
// Time complexity: O(1)
func (t *TwoSum) Add(num int) {
    t.data[num] = struct{}{}
}

// Find if there exists any pair of numbers which sum is equal to the value.
// Time complexity: O(n)
func (t *TwoSum) Find(target int) bool {
    for x := range t.data {
        if _, ok := t.data[target-x]; ok && x != target-x {
            return true
        }
    }
    return false
}

我投票结束这个问题,因为关于改进功能代码的问题属于@Michael,我认为我们需要首先澄清代码是否独立工作,如果代码无法独立工作,那么代码审查就脱离主题;否则,它可能在主题上。@ThomasWard“我的解决方案由于超出时间限制而失败。”在那里。它起作用了,还是不起作用。我两个都用电视机。测试用例14/16与以前一样失败。这是一个漫长的过程input@maeo输入多长时间?它应该以多快的速度执行?我想这是因为loop@maeo输入将有很多add()和find()-我不知道有多快-这是他们的测试用例
Set<Integer> nums = new HashSet<>();
type TwoSum struct {
    data map[int]struct{}
}

func New() *TwoSum {
    return &TwoSum{
        data: make(map[int]struct{}),
    }
}

// Add the number to the internal data structure.
// Time complexity: O(1)
func (t *TwoSum) Add(num int) {
    t.data[num] = struct{}{}
}

// Find if there exists any pair of numbers which sum is equal to the value.
// Time complexity: O(n)
func (t *TwoSum) Find(target int) bool {
    for x := range t.data {
        if _, ok := t.data[target-x]; ok && x != target-x {
            return true
        }
    }
    return false
}