日期:2014-05-20 浏览次数:20675 次
import java.util.*; public class FindMostInArray { public static void main(String args[]){ int[] intArray = {1,2,2,3,4,4,5,6,7,7,8,9}; List<Integer> list = new ArrayList<Integer> (); String str = ""; for(int i=0; i<intArray.length; i++){ str += String.valueOf(intArray[i]); } int MaxCount = 0; for(int i=0; i<intArray.length; i++){ String tempString = str.replaceAll(String.valueOf(intArray[i]), ""); int tempCount = str.length() - tempString.length(); if (tempCount > MaxCount){ list.clear(); list.add(intArray[i]); MaxCount = tempCount; } else if((tempCount == MaxCount) && (!list.contains(intArray[i]))){ list.add(intArray[i]); } } System.out.println("The most repeat number is: "+ MaxCount +"\nThe duplicated elements are: "+ list.toString()); } }
------解决方案--------------------
import java.util.HashMap;
import java.util.Iterator;
public class OnlyOne {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,3,3,1,2,1,1,6,7,5,7};
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for(int i=0; i<arr.length; i++){
hm.put(arr[i], hm.get(arr[i])==null?1:hm.get(arr[i])+1);
}
Iterator<Integer> iter = hm.keySet().iterator();
for(int i=iter.next(); iter.hasNext(); i=iter.next()){
if(hm.get(i) == 1){
System.out.println(i);
}
}
}
}
------解决方案--------------------
直方图统计
hist[arr[i]]=hist[arr[i]]+1;
------解决方案--------------------
6楼的就可以了
觉得不好的话,可以把HashMap改成int[50],然后参考7楼
------解决方案--------------------
代码:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] ta = {1, 2, 3, 4, 5, 3, 3, 1, 2, 1, 1, 6, 7, 5, 7};
int[] r = test(ta, 1);
System.out.println(Arrays.toString(r));
}
public static int[] test(int[] array, int count) {
if (array == null || array.length == 0 || count <= 0) return null;
int max = array[0];
for (int i = array.length - 1, j = 0; i > 0;) {
j = array[i--];
if (j < 0) return null;
if (max < j) max = j;
}
int[] t = new int[max + 1];
for (int i = array.length - 1; i >= 0;) {
t[array[i--]]++;
}
int[] r = new int[max + 1];
int j = 0;
for (int i = t.length - 1; i >= 0; i--) {
if (t[i] == count) r[j++] = i;
}
return Arrays.copyOf(r, j);
}
}