面试题02:Delete occurrences of an element if it occurs more than n times

题目描述
Alice and Bob were on a holiday. Both of them took many pictures of the places they’ve been, and now they want to show Charlie their entire collection. However, Charlie doesn’t like this sessions, since the motive usually repeats. He isn’t fond of seeing the Eiffel tower 40 times. He tells them that he will only sit during the session if they show the same motive at most N times. Luckily, Alice and Bob are able to encode the motive as a number. Can you help them to remove numbers such that their list contains each number only up to N times, without changing the order?

Task:
Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

Example:
EnoughIsEnough.deleteNth(new int[] {20,37,20,21}, 1) // return [20,37,21]

思路:*开始的时候打算用Map存储元素,在循环List的时候根据给定的最高次数N来判断该数是否应该从List中Remove掉,去除掉不符合条件的数以后,剩下的List即可满足条件。*但是对于最常用的的ArrayList而言,删除其中的元素存在陷阱,不易控制,增加了难度,后来用一个新的ArrayList来接收符合条件的数,最后将ArrayList转换成数组。
需要注意的是,删除ArrayList中的元素时,一般使用迭代器删除或者使用逆序循环删除的方式。
Answer:

public class Demo5 {
    public static int[] deleteNth(int[] elements, int maxOcurrences) {
    List<Integer> args = new ArrayList<Integer>();
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i : elements){
      if(map.containsKey(i)){
         int temp = map.get(i);
         if(temp < maxOcurrences){
             args.add(i);
             map.put(i, map.get(i)+1);
         }
          }
      else{
         map.put(i, 1);
         args.add(i);
      }  
    }
    int[] array = new int[args.size()]; 
    int n = 0;
    for(Integer i : args){
        array[n] = i;
        n++;
    }
    return array;
  }

还可以使用JavaScript来实现:

function compressArray(original, maxOccurrences) {
    if (!original) { return null; }
    if (maxOccurrences < 1) { return []; }

    var result = [];
    var itemCounts = {};
    for (var index = 0; index < original.length; index++){
        var item = original[index];
        var count = itemCounts[item] || 0;
        if (count < maxOccurrences) {
            result.push(item);
            itemCounts[item] = count + 1;
        }
    }

    return result;
}

需要注意的是

var count = itemCounts[item] || 0;

||表示当 itemCounts[item]的值不存在时取0;而

var itemCounts = {};

则定义了一个对象,其作用和Map有异曲同工之妙。
js的实现是从一篇问答上贴过来的
原位置在这

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值