删除重复

描述:

爱丽丝跟鲍勃去旅游,拍了很多照片回来,叫查理过来一起看照片。但是查理并不是很乐意,因为照片中有太多张重复了,他可不想看40多次埃菲尔铁塔。他对他们说,等你们把重复的照片删掉,最多保留N张,我再过来看。假设照片是一个整数数组,能否帮他们把数组中重复的数字删掉,最多保留N个呢?

例如:

Kata.DeleteNth (new int[] {20,37,20,21}, 1) // 返回 [20,37,21]
Kata.DeleteNth (new int[] {1,1,3,3,7,2,2,2,2}, 3) // 返回 [1, 1, 3, 3, 7, 2, 2, 2]

MyCode:

using System;
using System.Collections.Generic;
using System.Linq;

public class Kata {
  public static int[] DeleteNth(int[] arr, int x) 
  {
    var result = new List<int>();//实例化一个List<int>对象result
    foreach(var item in arr) //遍历数组,把相等数值小于x的数赋给result
    {
      if(result.Count(i => i == item) < x)
        result.Add(item);
    }
    return result.ToArray();
  }
}

CodeWar:

using System;
using System.Collections.Generic;
using System.Linq;

public class Kata {
  public static int[] DeleteNth(int[] arr, int x) {
    return arr.Where((t,i)=>arr.Take(i+1).Count(s=>s==t) <= x).ToArray();
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值