编程语言
首页 > 编程语言> > Java语言程序设计与数据结构(基础篇)chapter7 7.15

Java语言程序设计与数据结构(基础篇)chapter7 7.15

作者:互联网

消除重复

package com.sugarpie.classtest09;

import java.util.Scanner;

/**
 * @author sugarpie
 * @create 2021-04-20-9:01
 */
public class DeleteDupTest {
    public static int[] eliminateDuplicates(int[] list){
        int len = list.length;
        int[] newList = new int[len];
        int ptr = 0;
        newList[0] = list[0];
        for (int i = 0; i < len; i++) {
            int occur = 0;
            for (int j = 0; j < ptr; j++) {
                if (list[i] == list[j]){
                    list[j] = list[j + 1];
                    occur++;
                }
            }
            if (occur == 0){
                newList[ptr] = list[i];
                ptr++;
            }
        }
        int[] dick = new int[ptr];
        System.arraycopy(newList, 0, dick, 0, ptr);
        return dick;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter 10 numbers:");
        int[] list = new int[10];
        for (int i = 0; i < list.length; i++) {
            list[i] = input.nextInt();
        }
        int[] newList = eliminateDuplicates(list);
        for (int i = 0; i < newList.length; i++) {
            System.out.print(newList[i] + " ");
        }
    }
}

运行结果:

标签:7.15,Java,int,newList,chapter7,list,System,++,ptr
来源: https://blog.csdn.net/weixin_51032985/article/details/116983618