首页 新闻 会员 周边

如何获取一个数组中不重复的元素

0
[已解决问题] 解决于 2018-05-11 11:09
Integer[] array = new Integer[]{1,2,3,1,2,3,4};

如何取到4?

起个名字这么难?的主页 起个名字这么难? | 菜鸟二级 | 园豆:202
提问于:2018-05-09 18:05
< >
分享
最佳答案
0
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;

public class FindRepetition {
    private static final int index = 100000;
    private static int[] nums = new int[index];
    
    static {
        Random random = new Random();
        for(int i = 0; i < index; i++) {
            nums[i] = random.nextInt(index);
        }
    }
    
    public static void main(String... args) {
        long startTime1 = System.currentTimeMillis();
        List<Integer> result1 = findRepetitionTime(nums);
        System.out.println(String.format("时间效率优先,耗时:%s", (System.currentTimeMillis() - startTime1)));
        long startTime2 = System.currentTimeMillis();
        List<Integer> result2 = findRepetitionSpace(nums);
        System.out.println(String.format("时间效率优先,耗时:%s", (System.currentTimeMillis() - startTime2)));
    }
    
    //时间效率优先
    private static List<Integer> findRepetitionTime(int... nums) {
        List<Integer> result = new ArrayList<Integer>();
        Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(8);
        for(int num: nums) {
            if(countMap.containsKey(num)) {
                countMap.put(num, countMap.get(num));
            } else {
                countMap.put(num, 1);
            }
        }
        for(Map.Entry<Integer,Integer> entry: countMap.entrySet()) {
            if(entry.getValue() == 1) {
                result.add(entry.getKey());
            }
        }
        return result;
    }
    
    //空间效率优先
    private static List<Integer> findRepetitionSpace(int... nums) {
        List<Integer> result = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++) { 
            int count = 0;//标记重复次数
            for (int j = 0; j < nums.length; j++) {
                if(nums[i] != nums[j]) {
                    count++;
                }
                if(count==nums.length-1) {
                    result.add(nums[i]);
                    break;
                }
            }
        }
        return result;
    }
}

print:

时间效率优先,耗时:78
空间效率优先,耗时:8102

上面的代码是两种方法的时间对比,时间和空间自己衡量,至于那种方法更好,各有各的优点。第一个消耗的空间多一点,第二个耗时长一点

奖励园豆:5
飘云粟 | 菜鸟二级 |园豆:207 | 2018-05-10 10:53
其他回答(2)
0

C# 中可以用lambda

var temp=array.GroupBy(a => a).Where(b => b.Count() =1);之后可以直接循环取key值就好了

foreach (var r in temp)
  r.key;

华临天下 | 园豆:1501 (小虾三级) | 2018-05-09 20:36
0

for (int i = 0; i < array.length; i++) {
  int count = 0;//标记重复次数
  for (int j = 0; j < array.length; j++) {
    if(array[i] != array[j]) {
      count++;
    }
    if(count==array.length-1) {
      System.out.println(array[i]+"this is true");
      break;
    }
  }
}

这是一种思路,希望能帮到你。

地上有代码 | 园豆:100 (初学一级) | 2018-05-09 21:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册