![](/img/trans.png)
[英]Delete occurrences of an element if it occurs more than n times java. Internet solutions aren't working
[英]delete occurrences of an element if it occurs more than n times JAVA
public class EnoughIsEnough {
public static int[] deleteNth(int[] elements, int maxOccurrences){
int n = 0;
for(int b: elements){
for(int i =0 , i< elements.length;i++) {
if(elements[b] == elements[i]){
n++;
}
if (n > maxOccurrences) {
for(int k = b; k < elements.length -1 ; k ++) {
elements[k] = elements [k + 1];
}
}
}
}
return null;
}
}
嘿,我是一个完全的编程新手,只熟悉非常基础的知识,我遇到了这个问题:如果一个元素出现超过 n 次,我必须删除它,但我不知道我是否接近,我努力从数组中删除事件,我什至不确定我到目前为止编写的代码是否准确地检测到它们。 如果有人可以帮助我解决这个问题,我将不胜感激。 由于我的等级低,我无法查看代码大战的解决方案,并且由于我不理解复杂的代码,谷歌搜索这个问题并没有让我更接近。
public class EnoughIsEnough {
public static int[] deleteNth(int[] elements, int maxOccurrences){
HashMap<Integer, Integer> occurence = new HashMap<>();
for(int i : elements) {
if(occurence.containsKey(i)) {
occurence.put(i, occurence.get(i) + 1);
} else {
occurence.put(i, 1);
}
}
List<Integer> al = new ArrayList<>();
for(int i : elements) {
if(occurence.get(i) < maxOccurrences) {
al.add(i);
}
}
int[] output = new int[al.size()];
for(int i=0;i<al.size(); i++) {
output[i] = al.get(i);
}
return output;
}
}
您需要记住哪些元素超过了计数,因此您不会将它们添加到返回的数组中。
最好的方法是保持 map 中元素的频率计数,以便于参考。
int[] v = deleteNth(new int[] { 20, 37, 20, 21 }, 1); // return [20,37,21]
System.out.println(Arrays.toString(v));
v = deleteNth(new int[] { 1, 1, 2, 3, 3, 7, 2, 2, 2, 2 }, 3); // return [1, 1, 3, 3, 7, 2, 2, 2]
System.out.println(Arrays.toString(v));
印刷
[20, 37, 21]
[1, 1, 2, 3, 3, 7, 2, 2]
这是方法。 随着数字被添加到返回列表中,map 通过增加与数字关联的计数来记录它们。 如果计数超过允许的maxOccurrences
,则在遇到时不会将其添加到列表中。
public static int[] deleteNth(int[] elements,
int maxOccurrences) {
List<Integer> ret = new ArrayList<>();
Map<Integer, Integer> count = new HashMap<>();
for (int i : elements) {
count.compute(i, (k,v)-> v == null ? 1 : v + 1);
if (count.get(i) <= maxOccurrences) {
ret.add(i);
}
}
// here you could return the list or convert to an array (as I did) and return
// that.
return ret.stream().mapToInt(a->a).toArray();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.