codewars解题笔记---Merging sorted integer arrays (without duplicates)

题目:

Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.

解析:

编写一个函数,将两个排序后的数组合并为一个数组。数组只包含整数。此外,最终结果必须进行排序,不能有任何重复。

 

本题主要考察数组合并、去重、排序等问题

 

我的答案

 public static int[] mergeArrays(int[] first, int[] second) {
        Integer[] firstInteger = new Integer[first.length];//将int[]数组转化为Integer[]
       for (int i=0;i<firstInteger.length;i++){
           firstInteger[i] =first[i];
       }
       Integer[] secondInteger = new Integer[second.length];
       for (int i=0;i<secondInteger.length;i++){
           secondInteger[i] =second[i];
       }
        List<Integer> firstList = Arrays.asList(firstInteger);//将数组转化为list进行合并
        List<Integer> secondList = Arrays.asList(secondInteger);
        List<Integer> all = new ArrayList();
        all.addAll(firstList);
        all.addAll(secondList);
        List<Integer> result = new ArrayList();//去重
        for (int i=0;i<all.size();i++){
           if(!result.contains(all.get(i))){
                result.add(all.get(i));
           }
        }
       //转化会int类型,本来想用result.toArray转化为数组,但返回类型为Object[],要求返回int[]
        int[] res = new int[result.size()];
        for (int i=0;i<result.size();i++){
            res[i] =result.get(i).intValue();
        }
        Arrays.sort(res);
        return  res;
    }

 

最优答案

  public static int[] mergeArrays(int[] first, int[] second) {
    return IntStream.concat(IntStream.of(first),IntStream.of(second)).distinct().sorted().toArray();
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值