程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了以升序将元素插入ArrayList且没有重复的元素大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决以升序将元素插入ArrayList且没有重复的元素?

开发过程中遇到以升序将元素插入ArrayList且没有重复的元素的问题如何解决?下面主要结合日常开发的经验,给出你关于以升序将元素插入ArrayList且没有重复的元素的解决方法建议,希望对你解决以升序将元素插入ArrayList且没有重复的元素有所启发或帮助;

这是我的处理方式:(注释中的解释)

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);
}

您发布的当前解决方案看起来大部分都是正确的,除了它不会按升序保存元素的事实。

解决方法

我有一个家庭作业,需要在ArrayList<Interger>以下条件下插入或添加新元素:

  1. 元素必须 升序

  2. 中没有重复的 元素ArrayList<Integer>

  3. insert方法运行 O(n) 次。

这是我在添加新元素之前检查重复元素的插入方法。

    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

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 += "]";
    }

}

我需要插入大尺寸的元素,例如:

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

大佬总结

以上是大佬教程为你收集整理的以升序将元素插入ArrayList且没有重复的元素全部内容,希望文章能够帮你解决以升序将元素插入ArrayList且没有重复的元素所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: