Problem : Given an array of n integers. Find all the elements which occur more than n/3 times in the array.
Basic idea is to use negation technique. There can be only 2 elements which can exist more than n/3 times in a given array. Take two temp variables and two counters and scan the array. Every time a new elements is encountered, store it in the temp variable and increase the counter by one. If next element is same as one of the two temp variables then increase the respective counter. If next element is different then decrease the counter, If one of the counter reaches 0 then replace that element with the new found element and set the counter to 1(This works on the same technique of negation of elements in case 1 element was present more than n/2 times). If we consider each element occurring for more than n/3 times and count them and decrease the count when we encounter a different which is less than n/3 times. In the end we will be left with at least 1 count of elements which exist more than n/3 times.
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 | public List<Integer> majorityElement(int[] nums) { int countCheck = (nums.length/3) +1; int [] elements = new int[2]; int count1 = 0; int count2 =0; List<Integer> arrayList = new ArrayList<Integer>(); if(nums.length <1){ return arrayList; } if(nums.length == 1){ arrayList.add(nums[0]); return arrayList; } if(nums.length == 2 && nums[0] == nums[1]){ arrayList.add(nums[0]); return arrayList; } if(nums.length == 2 && nums[0] != nums[1]){ arrayList.add(nums[0]); arrayList.add(nums[1]); return arrayList; } for(int i = 0; i< nums.length; i++){ if(nums[i]== elements[0] || nums[i]==elements[1]){ if(nums[i] == elements[0]) count1++; else if(nums[i]== elements[1])count2++; }else if(count1==0){ elements[0] = nums[i]; count1++; }else if(count2 ==0){ elements[1]=nums[i]; count2++; }else { if(count1 >0){ count1--; } if(count2>0){ count2--; } } } count1=0; count2=0; System.out.println(elements[0]); System.out.println(elements[1]); for(int i=0; i< nums.length; i++){ if(elements[0]==nums[i]) count1++; if(elements[1] == nums[i]) count2++; } if(elements[0] != elements[1]){ if(count1 > (nums.length)/3 && nums.length>2){ arrayList.add(elements[0]); } if(count2 > (nums.length)/3 && nums.length >2){ arrayList.add(elements[1]); } }else{ arrayList.add(elements[0]); } return arrayList; } |
No comments:
Post a Comment