您的位置:首页 > 其它

Majority Number III

2016-01-22 06:57 337 查看
Question:

Given an array of integers and a number k, the majority number is the number that occurs
more than 1/k
of the size of the array.

Find it.

Example:

Given
[3,1,2,3,2,3,3,4,4,4]
and
k=3
, return
3
.


Analysis:
根据题目知道,majority number在数组中的个数要大于 n / k,所以最多只可能有k - 1个majority number(如果有k个,那么k * n / k 大于n,显然是不可能的)。维护一个size是k - 1的HashMap,key是数组中的值,value是该值在数组中的个数。遍历整个数组,如果该值已经在map中,则相对应的value加1。如果不存在,那么先检查map的size是否小于k - 1。是的话将该值添加进map中,然后value设为1。否则我们需要将map中所有key对应的value都减去1,如果value降到0,则从map中删去这个key。当整个数组遍历完,map中的值就是所有的可能的值。
这道题只要找唯一一个值,所以我们遍历map中的所有key,找到value最大的那个key就是我们要找的。

Code:

public class Solution {
/**
* @param nums: A list of integers
* @param k: As described
* @return: The majority number
*/
public int majorityNumber(ArrayList<Integer> nums, int k) {
if(nums == null || nums.size() == 0) {
return Integer.MIN_VALUE;
}

//most k - 1 values in the map
HashMap<Integer, Integer> counters = new HashMap<Integer, Integer>();
for(int num : nums) {
if(counters.containsKey(num)) {
counters.put(num, counters.get(num) + 1);
}else {
if(counters.size() < k - 1) {
counters.put(num, 1);
}else {
update(counters);
}
}
}

//corner case
if(counters.size() == 0) {
return Integer.MIN_VALUE;
}

//clear count
for(int key : counters.keySet()) {
counters.put(key, 0);
}

//recalculate the counter
for(int num : nums) {
if(counters.containsKey(num)) {
counters.put(num, counters.get(num) + 1);
}
}

int result = 0, maxCount = Integer.MIN_VALUE;
for(int key : counters.keySet()) {
int count = counters.get(key);
if(count > maxCount) {
result = key;
maxCount = count;
}
}

return result;
}

private void update(HashMap<Integer, Integer> counters) {
ArrayList<Integer> removeList = new ArrayList<Integer>();
for(int key : counters.keySet()) {
counters.put(key, counters.get(key) - 1);
if(counters.get(key) == 0) {
removeList.add(key);
}
}

for(int key : removeList) {
counters.remove(key);
}
}
}


Complexity:
时间复杂度是O(n * k)。

Reference: http://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-than-nk-times/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: