1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public class Moer {
public static int get2n(int[] nums){ int maj=nums[0],count=1; for (int j=1 ; j<nums.length;j++){ if(maj==nums[j]){ count++; }else count--; if(count==0){ maj=nums[j]; count=1; } } return maj; }
public static ArrayList<Integer> get3n(int[] array){ ArrayList<Integer> list = new ArrayList<Integer>(); if(array == null ||array.length == 0) return null; int maj1 = array[0],maj2 = array[0]; int count1 = 0,count2 = 0; int len = array.length; for(int i = 0;i<len;i++) { if(array[i] == maj1) count1++; else if(array[i] == maj2) count2++; else if(count1<=0) { count1 = 1; maj1 = array[i]; }else if(count2<=0) { count2 = 1; maj2 = array[i]; }else { --count1; --count2; } } count1 = count2 =0; for(int i =0;i<len;i++) { if(array[i] == maj1) count1++; if(array[i] == maj2) count2++; } if(count1>len/3) list.add(maj1); if(count2>len/3 & maj2!=maj1) list.add(maj2); return list; }
public static void solve3(int [] arr,int k) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int anArr:arr) { Integer value; if((value = map.get(anArr))!=null) { map.replace(anArr, value+1); }else { if(map.size() == k-1) { subtrackAll(map,k); }else { map.put(anArr,1); } } } map.keySet().forEach(integer->map.replace(integer, 0)); for(int num:arr) { Integer val; if((val = map.get(num))!= null) { map.replace(num, val+1); } } map.forEach((key,value)->{ if(value>arr.length/k) { System.out.println(key+" "); } }); } private static void subtrackAll(Map<Integer, Integer> map, int k) { List<Integer> list = new ArrayList(); map.forEach((integer,integer2)->{ if(integer2 == 1) { list.add(integer); }else map.replace(integer, integer2-1); }); if(list.size()!=0) { for(Integer key:list) { map.remove(key); } } } public static void main(String[] args) { int[] num2 ={1,1,-3,2,1}; System.out.println(get2n(num2));
int[] num4 = {1,1,1,1,1}; int[] num3 ={4,1,1,1,1,2,1,2,2,2,2,3,3,4}; System.out.println(get3n(num3));
solve3(num2,3); } }
|