Delete occurrences of an element if it occurs more than n times

Enough is enough!

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]
EnoughIsEnough.deleteNth(new int[] {1,1,3,3,7,2,2,2,2}, 3) // return [1, 1, 3, 3, 7, 2, 2, 2]

Good Solution1:

import java.util.*;

public class EnoughIsEnough {

  public static int[] deleteNth(int[] elements, int max) {
  
    if (max < 1) return new int[0];
    
    final HashMap<Integer,Integer> map = new HashMap<>();
    final List<Integer> list = new ArrayList<>();
    
    for (final Integer i : elements) {
      final Integer v = map.put(i, map.getOrDefault(i, 0) + 1);
      if (v == null || v < max) list.add(i);
    }
    
    return list.stream().mapToInt(i->i).toArray();
  }

}

Good Solution2:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class EnoughIsEnough {
    private static boolean shouldAdd(final Map<Integer, Integer> counts, final int element, final int maxOcurrences) {
        if (counts.getOrDefault(element, 0) < maxOcurrences) {
            counts.merge(element, 1, Integer::sum);
            return true;
        }
        return false;
    }

    static int[] deleteNth(final int[] elements, final int maxOcurrences) {
        final Map<Integer, Integer> counts = new HashMap<>();
        return Arrays.stream(elements)
            .filter(element -> shouldAdd(counts, element, maxOcurrences))
            .toArray();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,509评论 0 23
  • 写这个文的时候是因为看到大学一位同学C坐在同声传译的房间里,带着耳机,正在翻译的样子。估计你不会想到,几年前他和我...
    抹茶花开阅读 2,707评论 10 8
  • 董沛沛 洛阳 焦点网络五期 坚持原创分享第六十二天 两天出游回来,赶快读几页书。 焦点解决压力模式之语...
    缘源流长阅读 1,508评论 0 0
  • 逍遥在孤独的林子 温麻新姿 熬不过冬天的人,一定看不到春天!挺不住苦痛的人,一定得不到幸福!无论是破茧成蝶,还是鹰...
    温麻新姿A阅读 2,615评论 2 5
  • 从公司这样到现在好像还没休息,请假的时候也是满北京城跑的面试,转天又辗转去仲裁,经过一天的时间终于先把那个文件递交...
    狗蛋君阅读 1,229评论 0 0

友情链接更多精彩内容