日期:2014-05-20 浏览次数:20813 次
int count = 150; int[] num = new int[count]; for (int i=0; i<count; i++) { //生成随机数 num[i] = (int)(Math.random()*10); } Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); for (int i=0, j=0; i<count; i++) { //寻找最大距离 if (! map.containsKey(num[i])) { for (j=count-1; j>=i; j--) { if (num[j] == num[i]) { map.put(num[i], j-i-1); break; } } if (j<i) map.put(num[i], 0); } } for (Map.Entry<Integer, Integer> e : map.entrySet()) { //打印结果 System.out.printf("%s的最大距离%s\n", e.getKey(), e.getValue()); }
------解决方案--------------------
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Test{ public static void test(int count,int randomNum){ int[] data = new int[count]; for (int i=0; i<count; i++) { //生成随机数 data[i] = (int)(Math.random()*randomNum); } System.out.println(Arrays.toString(data)); Map<Integer,Integer[]> map = new HashMap<Integer,Integer[]>(); for(int i=0;i<count;i++){ int key = data[i]; if(map.containsKey(data[i])){ Integer[] temp =map.get(key); temp[1] = i-temp[0]; map.put(key,temp); } else{ map.put(key,new Integer[]{i,0}); } } for (Map.Entry<Integer, Integer[]> e : map.entrySet()) { //打印结果 System.out.printf("%s的最大距离%s\n", e.getKey(), e.getValue()[1]); } } public static void main(String[] args) { test(10,5); test(150,10); } }
------解决方案--------------------
用两个伴随数组遍历一次就行了
import java.util.Arrays; import java.util.Random; public class Test2 { static final int COUNT = 15; static int[] mArr = new int[COUNT]; public static void main(String[] args) { //产生随机数 Random random = new Random(); for(int i = 0;i < COUNT;i++) mArr[i] = random.nextInt(10); //获取最大距离 int[] pos = new int[10]; for(int i = 0;i < pos.length;i++){ pos[i] = -1; } int[] dis = new int[10]; for(int i = 0;i < COUNT;i++){ if(pos[mArr[i]] != -1) dis[mArr[i]] += (i - pos[mArr[i]] - 1); pos[mArr[i]] = i; } //输出 //System.out.println(Arrays.toString(mArr)); for(int i = 0;i < dis.length;i++){ if(dis[i] != 0) System.out.println(i + " 最长距离:" + dis[i]); } } }
------解决方案--------------------
生成随机数的楼上几位都写的,这里我就不写了直接遍历
/** * 遍历一次获得最大距离 * @param num * @param data * @return */ public static int test3(int[] num,int data){ int count=0; //计数1 int count2=0; //当遍历到相同的数值是计数加1 int count3=0; //最大长度 boolean flag=true; //是否首次匹配 for(int i=0;i<num.length;i++){ if(data==num[i]){ //如果匹配成功 if(flag){ flag=false; //设置为非首次 }else{ count3+=count; count=0; count2++; continue; } } if(!flag){ if(data!=num[i]){ count++; } } } count3+=count2-1; System.out.println("count3:"+count3); return count; } public static void main(String[] args) throws Exception { int [] num ={2,4,2,7,6,9,2,6,8}; test3(num,2); }