JAVA-数组经典练习题

有一个数组中有重复的元素, 去除重复元素(例如3个9,只留1个)

import java.util.Arrays;

/**
 * 1. 有一个数组中有重复的元素, 去除重复元素(例如3个9,只留1个)
 * @author admin
 */
public class Xample01 {

    public static void main(String[] args) {
       //预期结果:1,3,5,8,9
       int [] arr = {0,1,3,1,1,5,8,8,8,0,9,5};
       System.out.println(Arrays.toString(arr));
       //创建一个临时数组
       int [] temp = new int[arr.length];
       System.out.println(Arrays.toString(temp));
       //遍历元素组,比较插入临时数组中。
       int count = 0;
       for (int i = 0; i < arr.length; i++) {
          boolean existsTemp = false;
          for (int j = 0; j < count; j++) {
            //比较
             if(arr[i] == temp[j]){
                 //相等,我们就终止比较。
                 existsTemp = true;
                 break;
             }
          }
          if(!existsTemp){
              temp[count] = arr[i];
              count++;  
          }
       }
       temp = Arrays.copyOf(temp, count);
       System.out.println(Arrays.toString(temp));
    }

}
 

找出一个数组中有哪些重复元素, 并且这些元素各重复了几次

import java.util.Arrays;

public class Xample02 {

    public static void main(String[] args) {
         //预期结果:1,3,5,8,9
           int [] arr = {0,1,3,1,1,5,8,8,8,0,9,5};
           System.out.println(Arrays.toString(arr));
           //创建一个临时数组
           int [] temp = new int[arr.length];
           System.out.println(Arrays.toString(temp));
           //遍历元素组,比较插入临时数组中。
           int count = 0;
           for (int i = 0; i < arr.length; i++) {
              boolean existsTemp = false;
              for (int j = 0; j < count; j++) {
                //比较
                 if(arr[i] == temp[j]){
                     //相等,我们就终止比较。
                     existsTemp = true;
                     break;
                 }
              }
              if(!existsTemp){
                  temp[count] = arr[i];
                  count++;  
              }
           }
           temp = Arrays.copyOf(temp, count);
           System.out.println(Arrays.toString(temp));
           for (int i = 0; i < temp.length; i++) {
              int size = 0;
              for (int j = 0; j < arr.length; j++) {
                  if(temp[i] == arr[j]){
                      size++;
                  }
              }
              if(size > 1){
                  System.out.println("元素"+temp[i]+"重复的次数为:"+(size-1)); 
              }
              
           }

    }

}
 

猜你喜欢

转载自blog.csdn.net/Mr_zdk/article/details/82797635