删除元素的出现次数超过n次 [英] Delete occurrence of an element is it occurs more than n times

查看:77
本文介绍了删除元素的出现次数超过n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果超过n的数量,我需要删除该值,例如:

I would need to erase the value if it exceeds the number of n, for example:

sortN([2, 3, 3, 3, 4, 4], 1);-> [2, 3, 4]



换句话说,出现的次数不应超过n。我一直在尝试用不同的方法解决这个问题,但仍然无法获得所需的输出



我尝试过:



我得到的最接近的是计算每个元素的出现次数,如下所示:


In other words, the number of occurrences should not exceed n. I have been trying tackle this problem with different approaches but still can`t get the desired output

What I have tried:

The closest I got was to count number of occurrences of every element, like this:

function compressArray(original) {
 
	var compressed = [];
	// make a copy of the input array
	var copy = original.slice(0);
 
	// first loop goes over every element
	for (var i = 0; i < original.length; i++) {
 
		var myCount = 0;	
		// loop over every element in the copy and see if it's the same
		for (var w = 0; w < copy.length; w++) {
			if (original[i] == copy[w]) {
				
				myCount++;
				
				delete copy[w];
			}
		}
 
		if (myCount > 0) {
		
			compressed.push(original[i], myCount);
		}
	}
 
	return compressed;
};



这真的有用吗?我应该采取不同的方法吗?


Is this really useful? Should I take a different approach?

推荐答案

这样的事情怎么样:

How about something like this:
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;
}



演示 [ ^ ]


这篇关于删除元素的出现次数超过n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆