Advertisement
Guest User

Untitled

a guest
Jun 11th, 2016
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. vector<int> majorityElement(vector<int>&nums, int k) {
  2.     vector<int> result;
  3.     if (k < 2) return result;
  4.     // there are at most k-1 candidates
  5.     vector<int> candidates(k-1, 0);
  6.     vector<int> count(k-1, 0);
  7.  
  8.     // initialize candidates array with different values
  9.     // otherwise, the all zeros nums vector will fail
  10.     for (int i = 0; i < k-1; ++i)
  11.         candidates[i] = i;
  12.  
  13.     // first loop, if one candidate appears more than n/k times,
  14.     // the maximal number of times it can be offset by other candidates is n/k
  15.     for (int num : nums) {
  16.         bool found = false;
  17.         for (int j = 0; j < k-1; ++j) {
  18.             if (num == candidates[j]) {
  19.                 ++count[j];
  20.                 found = true;
  21.                 break;
  22.             }
  23.         }
  24.  
  25.         if (!found) {
  26.             for (int j = 0; j < k-1; ++j) {
  27.                 if (count[j] == 0) {
  28.                     candidates[j] = num;
  29.                     ++count[j];
  30.                     found = true;
  31.                     break;
  32.                 }
  33.             }
  34.         }
  35.         if (!found) {
  36.             for (int j = 0; j < k-1; ++j) {
  37.                 --count[j];
  38.             }
  39.         }
  40.     }
  41.  
  42.     // second loop: find candidates that appear more than n/k times
  43.     count.assign(k-1, 0);
  44.     for (int num : nums) {
  45.         for (int j = 0; j < k-1; ++j) {
  46.             if (candidates[j] == num)
  47.                 ++count[j];
  48.         }
  49.     }
  50.  
  51.     for (int j = 0; j < k-1; ++j) {
  52.         if (count[j] > nums.size()/k)
  53.             result.push_back(candidates[j]);
  54.     }
  55.     return result;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement