2015-12-14 116 views
2

我遇到了称为compress的这个问题。目标是获取一个数组,删除任何重复的值并返回一个新的数组。将数组值压缩到另一个数组中

我知道这很容易与ArrayList s,但我想没有他们这样做。

到目前为止,我刚刚写了一个循环来确定唯一值的数量,以便我可以构造一个适当长度的新数组。那么我怎样才能将唯一的值加入到新的数组中?

public static int[] compress(int[] array){ 
    int length = 0; 
    boolean contains = false; 
    for (int i = 0; i < array.length; i++){ 
     contains = false; 
     for (int j = 0; j < i; j++){ 
      if (a[i] == a[j]){ 
       contains = true; 
       j = i; 
      } else { 
       contains = false; 
      } 
     } 
     if (!contains){ 
      length++; 
     } 
    } 

    int[] uniqueArray = new int[length];   
} 
+0

创建一个新的原始数组长度相等的数组,从原始数组中只复制一个数值(因此没有重复数据),跟踪最后添加数值的位置。使用'Arrays.copyOf'将所有唯一值(这就是为什么你需要这个“最后一个位置”值)复制到一个满足它新数据大小的数组中 – MadProgrammer

+1

用计算方式来思考排序:定义一个数组,其大小为max - min + 1);迭代你的输入数组,并把count放到counter数组中;遍历计数器数组并选取其值大于零的索引。 – chinglun

回答

0

未经测试,但我认为这应该会有诀窍。

public static int[] copyArray(int [] num){ 
    int x = 0; 
    int numDuplicate = 0; 
    int[] copy = new int[num.length]; // we use this to copy the non duplicates 
    HashMap<Integer, Integer> count = new HashMap<>(); //hashmap to check duplicates 
    for(int i = 0; i < num.length; i++){ 
     if(count.containsKey(num[i])){ 
      count.put(num[i], count.get(num[i])+1); 
      numDuplicate++; // keep track of duplicates 
     }else{ 
      count.put(num[i], 1); // first occurence 
      copy[x] = num[i]; // copy unique values, empty values will be at end 
      x++; 
     } 
    } 
    // return only what is needed 
    int newSize = num.length - numDuplicate; 
    int[] copyNum = new int[newSize]; 
    for(int i = 0; i < copyNum.length; i++){ 
     copyNum[i] = copy[i]; 
    } 
    return copyNum; 
} 


public static void main(String[] args) { 
    // sample elements 
    int[] nums = new int[20]; 
    for(int i = 0; i < nums.length; i++){ 
     nums[i] = (int)(Math.random() * 20); 
    } 
    System.out.println(Arrays.toString(nums)); 
    System.out.println(Arrays.toString(copyArray(nums))); 

}