问题描述
限时送ChatGPT账号..我有一个家庭作业,我需要在 ArrayList
中插入或添加新元素,条件如下:
I have a homework assignment where I need to insert or add new elemment into ArrayList<Interger>
with follow condition:
元素必须升序.
ArrayList
插入方法运行 O(n) 次.
这是我在添加新元素之前检查重复元素的插入方法.
Here is my insert method for check duplicate element before add new element.
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); }
}
我该怎么做?谢谢.
添加
这是我的类名 InSetExtra
here is my class names 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 += "]";
}
}
我需要插入大尺寸的元素,例如:
and i need to insert a large size of elements, for example:
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));
我该怎么办?
ps.我的导师只需要使用 ArrayList
ps. my instructor need to use only ArrayList
推荐答案
我会这样做:(评论中的解释)
Here is how I would do it: (Explanation in comments)
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);
}
您发布的当前解决方案看起来基本正确,只是它不会按升序保存元素.
The current solution that you posted looks mostly correct, except for the fact that it will not save elements in ascending order.
这篇关于以升序将元素插入到 ArrayList 并且没有重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论