【发布时间】:2021-04-18 12:28:12
【问题描述】:
我正在做一个显然需要使用 Set 的问题,但我需要按插入顺序从集合中检索元素 + 检索特定元素。
但是找到特定元素太慢了(我猜是O(n),因为我必须遍历整个集合才能找到并返回它)。
所以我选择了LinkedHashMap<someClass,someClass>,其中键值映射包含相同的对象。
虽然这样更快,但它占用了两倍的内存,如果我的键/值(无论如何都相同)碰巧占用了大量空间,这尤其令人担忧。
我希望是否有人对我的问题或优化有更好的解决方案。
编辑: 顺便说一句,SO answer 的 cmets 可能会有所帮助
编辑:
public Set<CompanyDummy> run(int numberOfCompanies)
{
Set<CompanyDummy> companies=new LinkedHashSet<>();
//Create companies
CompanyDummy company;
for(int idx=0;idx<=numberOfCompanies-1;idx++)
{
company=new CompanyDummy(idx);
companies.add(company);
}
//Some code here to fill up each CompanyDummy element with engineers
//At this point,there will be input
//specifying which companies to merge via their index(not reference)
//Problem guarantees those companies exist. Hence, my reason why
//I didn't do something like
//if (set.contains(value)) return value;
//Do note when we merge companies u & v, v is closed down
for(int idx=0;idx<=transactions-1;idx++)
{
companyID= scanner.nextInt();
anotherCompanyID= scanner.nextInt();
//This part is where I search through companies to find if one exists
//which is O(n)
//Replacing sets with maps somehow makes the program faster
//despite LinkedHashSet being backed by LinkedHashMap
company=findCompany(companies, companyID);
anotherCompany=findCompany(companies, anotherCompanyID);
if(company!=null && anotherCompany!=null)
{
company.union(anotherCompany);
companies.remove(anotherCompany);
}
}
}
private CompanyDummy findCompany(Set<CompanyDummy> companies,int id)
{
for(CompanyDummy company : companies)
{
if(company.getIndex()==id)
{
return company;
}
}
return null;
}
}
class CompanyDummy
{
private int index;
private Set<Integer> engineers;//The Integer here just denotes the engineer
public CompanyDummy(int index)
{
this.index=index;
}
public int getindex()
{
return index;
}
public void union(CompanyDummy someCompany)
{
this.engineers.addAll(someCompany.engineers);
}
}
【问题讨论】:
-
您能解释一下 LinkedHashSet 为何不适合您的使用吗?
-
有一点,正如我所说,我必须检索特定元素。这部分导致我的程序对于大输入非常慢。
标签: java dictionary set time-complexity disjoint-sets