我有一个家庭作业,我需要插入或添加新的元素ArrayList<Interger>与以下条件:
元素必须按升序排列.
没有重复的元素ArrayList<Integer>
插入方法在O(n)次运行.
这是我在添加新元素之前检查重复元素的insert方法.
public void insert(int x){
//effect: Check duplicate elements if not x to the elements;
boolean found = false;
if(super.size()!=0){
for(int i=0; i<super.size(); i++){
if(super.get(i)==x){
found = true;
}
}
}
if(found){ return; }
else{ super.add(x); }
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?谢谢.
加成
这是我的类名InSetExtra
public class IntSetExtra extends ArrayList<Integer> {
private static final long serialVersionUID = 1L;
public IntSetExtra(){
super();
}
public void insert(int x){
//effect: Check duplicate elements if not x to the elements;
boolean found = false;
if(super.size()!=0){
for(int i=0; i<super.size(); i++){
if(super.get(i)==x){
found = true;
}
}
}
if(found){ return; }
else{ super.add(x); }
}
public String toString(){
//effect: return string of this.
if(super.size()==0) return "[]";
String s = "[" + super.get(0).toString();
for(int i=1; i<super.size(); i++){
s += ", " + super.get(i).toString();
}
return s += "]";
}
}
Run Code Online (Sandbox Code Playgroud)
我需要插入大尺寸的元素,例如:
IntSetExtra a, b;
a = new IntSetExtra();
b = new IntSetExtra();
for(int i=0; i<30000; i++){ a.insert(2*i); }
for(int i=0; i<30000; i++){ a.insert(i); }
System.out.println("a sub = "+a.toString().substring(0, 37));
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
PS.我的教师只需要使用ArrayList
Mau*_*rry 25
这是O(n)中的插入方法.
public void insert(int x) {
int pos = Collections.binarySearch(this, x);
if (pos < 0) {
add(-pos-1, x);
}
}
Run Code Online (Sandbox Code Playgroud)
我将如何做到这一点:(评论中的解释)
public void insert(int x){
// loop through all elements
for (int i = 0; i < size(); i++) {
// if the element you are looking at is smaller than x,
// go to the next element
if (get(i) < x) continue;
// if the element equals x, return, because we don't add duplicates
if (get(i) == x) return;
// otherwise, we have found the location to add x
add(i, x);
return;
}
// we looked through all of the elements, and they were all
// smaller than x, so we add ax to the end of the list
add(x);
}
Run Code Online (Sandbox Code Playgroud)
您发布的当前解决方案看起来大致正确,除了它不会按升序保存元素.