Это должно быть так:
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
Распаковка должна быть в фазе генерации ресурсов, потому что, если в фазе пакета не будут включены в качестве ресурсов. Попробуйте очистить пакет, и вы увидите.
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
Попробуйте этот ответ. Во-первых, данные:
int[] a = {1,2,3,4,5,6,7,7,7,7};
Здесь мы строим карту, подсчитывающую количество раз, когда появляется каждое число:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count+1 : 0);
}
Теперь мы найдем число с максимальной частотой и возвращаем его:
Integer popular = Collections.max(map.entrySet(),
new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}).getKey();
Как вы можете видеть, самым популярным номером является семь:
System.out.println(popular);
> 7
EDIT
Вот мой ответ без , используя карты, списки и т. д. и используя только массивы; хотя я сортирую массив на месте. Это сложность O (n log n), лучше, чем принятое решение O (n ^ 2).
public int findPopular(int[] a) {
if (a == null || a.length == 0)
return 0;
Arrays.sort(a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] == previous)
count++;
else {
if (count > maxCount) {
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[a.length-1] : popular;
}
public class MostFrequentIntegerInAnArray {
public static void main(String[] args) {
int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
System.out.println("Most common item = "+getMostFrequentInt(items));
}
//Time Complexity = O(N)
//Space Complexity = O(N)
public static int getMostFrequentInt(int[] items){
Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
for(int item : items){
if(!itemsMap.containsKey(item))
itemsMap.put(item, 1);
else
itemsMap.put(item, itemsMap.get(item)+1);
}
int maxCount = Integer.MIN_VALUE;
for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
if(entry.getValue() > maxCount)
maxCount = entry.getValue();
}
return maxCount;
}
}
Надеюсь, это поможет. public class Ideone {public static void main (String [] args) throws java.lang.Exception {
int[] a = {1,2,3,4,5,6,7,7,7};
int len = a.length;
System.out.println(len);
for (int i = 0; i <= len - 1; i++) {
while (a[i] == a[i + 1]) {
System.out.println(a[i]);
break;
}
}
}
}
Mine Linear O (N)
Используя карту, чтобы сохранить все элементы differents, найденные в массиве, и сохранить количество раз, а затем просто получить максимальный размер от карты.
import java.util.HashMap;
import java.util.Map;
public class MosftOftenNumber {
// for O(N) + map O(1) = O(N)
public static int mostOftenNumber(int[] a)
{
Map m = new HashMap<Integer,Integer>();
int max = 0;
int element = 0;
for(int i=0; i<a.length; i++){
//initializing value for the map the value will have the counter of each element
//first time one new number its found will be initialize with zero
if (m.get(a[i]) == null)
m.put(a[i],0);
//save each value from the array and increment the count each time its found
m.put(a[i] , (int)m.get(a[i]) + 1);
//check the value from each element and comparing with max
if ((int)m.get(a[i])>max){
max = (int) m.get(a[i]);
element = a[i];
}
}
return element;
}
public static void main(String args[]) {
// int[] array = {1,1,2,1,1};
// int[] array = {2,2,1,2,2};
int[] array = {2,2,1,3,3,5,5,6,6,7,7,9,9,10,10,10,10,11,12,13,14,15,15,1,15,15,1,15,15};
System.out.println(mostOftenNumber(array));
}
}
int largest = 0;
int k = 0;
for (int i = 0; i < n; i++) {
int count = 1;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count > largest) {
k = a[i];
largest = count;
}
}
Итак, здесь n
- длина массива, а a[]
- ваш массив.
Сначала возьмите первый элемент и проверьте, сколько раз он повторяется, и увеличивайте counter (count
), чтобы узнать, сколько раз это происходит. Проверьте, действительно ли это максимальное количество раз, когда число дало, если да, затем измените самую большую переменную (чтобы сохранить максимальное количество повторений), и если вы хотите также сохранить эту переменную, вы можете сделать это в другой переменной (здесь k
).
Я знаю, что это не самый быстрый, но, безусловно, самый простой способ понять
Предполагая, что ваш массив int отсортирован, я бы сделал ...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
public class MostFrequentNumber {
public MostFrequentNumber() {
}
int frequentNumber(List<Integer> list){
int popular = 0;
int holder = 0;
for(Integer number: list) {
int freq = Collections.frequency(list,number);
if(holder < freq){
holder = freq;
popular = number;
}
}
return popular;
}
public static void main(String[] args){
int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};
List<Integer> list = new ArrayList<Integer>();
for(Integer num : numbers){
list.add(num);
}
MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();
System.out.println(mostFrequentNumber.frequentNumber(list));
}
}
Значение элементов массива должно быть меньше длины массива для этого:
public void findCounts(int[] arr, int n) {
int i = 0;
while (i < n) {
if (arr[i] <= 0) {
i++;
continue;
}
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
}
else {
arr[elementIndex]--;
arr[i] = 0;
i++;
}
}
Console.WriteLine("Below are counts of all elements");
for (int j = 0; j < n; j++) {
Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
}
}
Сложность времени будет O(N)
, а сложность пространства будет O(1)
.
Предполагая, что ваш массив отсортирован (например, тот, который вы опубликовали), вы можете просто перебирать массив и считать самый длинный сегмент элементов, это что-то вроде сообщения @ narek.gevorgyan, но без ужасно большого массива, и он использует тот же объем памяти независимо от размера массива:
private static int getMostPopularElement(int[] a){
int counter = 0, curr, maxvalue, maxcounter = -1;
maxvalue = curr = a[0];
for (int e : a){
if (curr == e){
counter++;
} else {
if (counter > maxcounter){
maxcounter = counter;
maxvalue = curr;
}
counter = 0;
curr = e;
}
}
if (counter > maxcounter){
maxvalue = curr;
}
return maxvalue;
}
public static void main(String[] args) {
System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}
Если массив не отсортирован, сортируйте его с помощью Arrays.sort(a);
Если вы не хотите использовать карту, просто выполните следующие шаги:
Arrays.sort()
) public static void main(String[] args) {
int[] myArray = {1,5,4,4,22,4,9,4,4,8};
Map<Integer,Integer> arrayCounts = new HashMap<>();
Integer popularCount = 0;
Integer popularValue = 0;
for(int i = 0; i < myArray.length; i++) {
Integer count = arrayCounts.get(myArray[i]);
if (count == null) {
count = 0;
}
arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
if (count > popularCount) {
popularCount = count;
popularValue = myArray[i];
}
}
System.out.println(popularValue + " --> " + popularCount);
}
Похоже, что вы ищете значение режима (статистический режим), посмотрите на Документы Apache для статистических функций.
Лучшим подходом будет использование карты, где ключ будет элементом, а значением будет отсчет каждого элемента. Наряду с этим сохраняем массив размеров, который будет содержать индекс самого популярного элемента. Заполняем этот массив при самой конструкции карты, чтобы нам снова не пришлось перебирать карту.
Подход 2: -
Если кто-то хочет пойти с двумя циклами, вот импровизация из принятого ответа, когда нам не нужно начинать второй цикл с каждого раза
public class TestPopularElements {
public static int getPopularElement(int[] a) {
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++) {
temp = a[i];
tempCount = 0;
for (int j = i+1; j < a.length; j++) {
if (temp == a[j])
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void main(String[] args) {
int a[] = new int[] {1,2,3,4,5,6,2,7,7,7};
System.out.println("count is " +getPopularElement(a));
}
}
public static int getMostCommonElement(int[] array) {
Arrays.sort(array);
int frequency = 1;
int biggestFrequency = 1;
int mostCommonElement = 0;
for(int i=0; i<array.length-1; i++) {
frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
if(frequency>biggestFrequency) {
biggestFrequency = frequency;
mostCommonElement = array[i];
}
}
return mostCommonElement;
}
package frequent;
import java.util.HashMap;
import java.util.Map;
public class Frequent_number {
//Find the most frequent integer in an array
public static void main(String[] args) {
int arr[]= {1,2,3,4,3,2,2,3,3};
System.out.println(getFrequent(arr));
System.out.println(getFrequentBySorting(arr));
}
//Using Map , TC: O(n) SC: O(n)
static public int getFrequent(int arr[]){
int ans=0;
Map<Integer,Integer> m = new HashMap<>();
for(int i:arr){
if(m.containsKey(i)){
m.put(i, m.get(i)+1);
}else{
m.put(i, 1);
}
}
int maxVal=0;
for(Integer in: m.keySet()){
if(m.get(in)>maxVal){
ans=in;
maxVal = m.get(in);
}
}
return ans;
}
//Sort the array and then find it TC: O(nlogn) SC: O(1)
public static int getFrequentBySorting(int arr[]){
int current=arr[0];
int ansCount=0;
int tempCount=0;
int ans=current;
for(int i:arr){
if(i==current){
tempCount++;
}
if(tempCount>ansCount){
ansCount=tempCount;
ans=i;
}
current=i;
}
return ans;
}
}
ниже код может быть помещен в основной метод
// TODO Auto-generated method stub
Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
Set<Integer> set = new HashSet<Integer>(list);
int highestSeq = 0;
int seq = 0;
for (int i : set) {
int tempCount = 0;
for (int l : list) {
if (i == l) {
tempCount = tempCount + 1;
}
if (tempCount > highestSeq) {
highestSeq = tempCount;
seq = i;
}
}
}
System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
import java.util.Scanner;
public class Mostrepeatednumber
{
public static void main(String args[])
{
int most = 0;
int temp=0;
int count=0,tempcount;
Scanner in=new Scanner(System.in);
System.out.println("Enter any number");
int n=in.nextInt();
int arr[]=new int[n];
System.out.print("Enter array value:");
for(int i=0;i<=n-1;i++)
{
int n1=in.nextInt();
arr[i]=n1;
}
//!!!!!!!! user input concept closed
//logic can be started
for(int j=0;j<=n-1;j++)
{
temp=arr[j];
tempcount=0;
for(int k=1;k<=n-1;k++)
{
if(temp==arr[k])
{
tempcount++;
}
if(count<tempcount)
{
most=arr[k];
count=tempcount;
}
}
}
System.out.println(most);
}
}
Это неправильный синтаксис. Когда вы создаете анонимный массив, вы НЕ ДОЛЖНЫ указывать его размер.
Когда вы пишете следующий код:
new int[] {1,23,4,4,5,5,5};
Вы здесь создаете анонимный массив int, размер которого будет определен по количеству значений, которые вы указываете в фигурных скобках.
Вы можете назначить эту ссылку, как вы это сделали, но это будет правильный синтаксис для этого же: -
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Теперь просто Sysout с правильной позицией индекса:
System.out.println(a[7]);
Вы можете подсчитать вхождения разных чисел, а затем искать самый высокий. Это пример, который использует карту, но может быть легко адаптирован к встроенным массивам.
Второй по величине элемент: возьмем пример: [1,5,4,2,3] в этом случае, Второй наибольший элемент будет 4.
private static int getMostOccuringElement (int [] A) {Map occuringMap = new HashMap ();
//count occurences
for (int i = 0; i < A.length; i++) {
if (occuringMap.get(A[i]) != null) {
int val = occuringMap.get(A[i]) + 1;
occuringMap.put(A[i], val);
} else {
occuringMap.put(A[i], 1);
}
}
//find maximum occurence
int max = Integer.MIN_VALUE;
int element = -1;
for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
element = entry.getKey();
}
}
return element;
}