int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
如何编写方法并返回7?
我希望在没有列表,地图或其他助手的帮助下保持原生。 只有数组[]。
答案 0 :(得分:72)
试试这个答案。首先,数据:
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
修改强>
这是我的回答
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;
}
答案 1 :(得分:33)
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;
}
答案 2 :(得分:8)
答案 3 :(得分:6)
假设您的数组已经排序(就像您发布的数组一样),您可以简单地遍历数组并计算最长的元素段,它类似于@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);
答案 4 :(得分:4)
使用 Java 8 Streams
int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), counting()));
int max = count.entrySet().stream()
.max((first, second) -> {
return (int) (first.getValue() - second.getValue());
})
.get().getKey();
System.out.println(max);
<强>解释强>
我们将int[] data
数组转换为盒装整数流。然后我们通过groupingBy
收集元素,并使用辅助计数收集器在groupBy
之后进行计数。
最后,我们通过使用流和lambda比较器再次基于计数对元素->
计数的映射进行排序。
答案 5 :(得分:3)
这个没有地图:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
System.out.println(getMostPopularElement(a));
}
private static int getMostPopularElement(int[] a) {
int maxElementIndex = getArrayMaximumElementIndex(a);
int[] b = new int[a[maxElementIndex] + 1]
for (int i = 0; i < a.length; i++) {
++b[a[i]];
}
return getArrayMaximumElementIndex(b);
}
private static int getArrayMaximumElementIndex(int[] a) {
int maxElementIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[maxElementIndex]) {
maxElementIndex = i;
}
}
return maxElementIndex;
}
}
如果您的数组可以包含< 0
的元素,则只需更改一些代码。
当你的数组项不是大数字时,这个算法很有用。
答案 6 :(得分:2)
如果您不想使用地图,请按以下步骤操作:
Arrays.sort()
)答案 7 :(得分:2)
数组元素值应小于此数组的数组长度:
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)
。
答案 8 :(得分:1)
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;
}
}
答案 9 :(得分:1)
假设您的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);
答案 10 :(得分:1)
最佳方法是使用map,其中key将是元素,value将是每个元素的计数。与此一起保持一个包含最流行元素索引的大小数组。在地图构建本身时填充此数组,以便我们不必再次遍历地图。
方法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));
}
}
答案 11 :(得分:1)
Mine Linear O(N)
使用map保存数组中找到的所有不同元素,并保存出现的次数,然后从地图中获取最大值。
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));
}
}
答案 12 :(得分:1)
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);
}
}
答案 13 :(得分:1)
好像您正在寻找模式值(统计模式),请查看统计函数的Apache's Docs。
答案 14 :(得分:0)
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
public static void main(String [] args){
int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
Map map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < arrayToCheckFrom.length; i++){
int sum = 0;
for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
sum += 1;
}
map.put(arrayToCheckFrom[i], sum);
}
System.out.println(getMaxValue(map));
}
public static Integer getMaxValue( Map<Integer,Integer> map){
Map.Entry<Integer,Integer> maxEntry = null;
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
maxEntry = pair;
}
}
return maxEntry.getKey();
}
}
答案 15 :(得分:0)
此方法返回并包含所有流行元素的数组,以防有多个重复次数相同的重复元素:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.burhanuday.wordpressblog"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation "com.jakewharton:butterknife:8.8.1"
annotationProcessor "com.jakewharton:butterknife-compiler:8.8.1"
implementation "com.squareup.retrofit2:retrofit:2.4.0"
implementation "com.squareup.retrofit2:converter-gson:2.4.0"
implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0"
implementation "com.squareup.okhttp3:okhttp:3.10.0"
implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.1"
implementation 'com.asksira.android:webviewsuite:1.0.3'
implementation 'com.android.support:customtabs:28.0.0'
implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
}
答案 16 :(得分:0)
比较两个数组,希望对您有用。
public static void main(String []args){
int primerArray [] = {1,2,1,3,5};
int arrayTow [] = {1,6,7,8};
int numberMostRepetly = validateArrays(primerArray,arrayTow);
System.out.println(numberMostRepetly);
}
public static int validateArrays(int primerArray[], int arrayTow[]){
int numVeces = 0;
for(int i = 0; i< primerArray.length; i++){
for(int c = i+1; c < primerArray.length; c++){
if(primerArray[i] == primerArray[c]){
numVeces = primerArray[c];
// System.out.println("Numero que mas se repite");
//System.out.println(numVeces);
}
}
for(int a = 0; a < arrayTow.length; a++){
if(numVeces == arrayTow[a]){
// System.out.println(numVeces);
return numVeces;
}
}
}
return 0;
}
答案 17 :(得分:0)
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;
}
答案 18 :(得分:0)
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[]
就是你的数组。
首先,取第一个元素并检查它重复的次数并增加计数器(count
)以查看它发生的次数。
如果是,则检查一个数字到目前为止的最大次数是否发生,然后更改最大变量(以存储最大重复次数),如果您还想存储变量,则可以在另一个变量中执行此操作(这里k
)。
我知道这不是最快的,但绝对是理解
的最简单方法答案 19 :(得分:0)
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;
}
}
答案 20 :(得分:0)
下面的代码可以放在主方法
中 // 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);
答案 21 :(得分:0)
答案 22 :(得分:-1)
您可以计算不同数字的出现次数,然后查找最高的数字。这是一个使用Map的示例,但可以相对容易地适应本机数组。
第二大元素: 让我们举个例子:[1,5,4,2,3]在这种情况下, 第二大元素将是4.
排序完成输出后,按降序对数组进行排序 A = [5,4,3,2,1]
使用索引1从排序后的数组中获取第二大元素。[1] - &gt;这将给出第二大元素4。
private static int getMostOccuringElement(int [] A){ 映射occuringMap = new HashMap();
O(Q*Sqrt(N))
答案 23 :(得分:-1)
我希望这会有所帮助。 公共类Ideone { public static void main(String [] args)抛出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;
}
}
}
}
答案 24 :(得分:-1)
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));
}
}
答案 25 :(得分:-3)
这是错误的语法。当你创建一个匿名数组时,你不能给它的大小。
编写以下代码时:
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]);