avatar
amex的blue nile offer# Money - 海外理财
S*C
1
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.
Note
There is only one majority number in the array.
Example
For [3,1,2,3,2,3,3,4,4,4] and k = 3, return 3
Challenge
O(n) time and O(k) extra space
public class Solution {
/**
* @param nums: A list of integers
* @param k: As described
* @return: The majority number
*/
public int majorityNumber(ArrayList nums, int k) {
// write your code
}
}
http://lintcode.com/en/problem/majority-number-iii/
avatar
l*l
2
记得以前看过amex有过blue nile的offer,有谁用过这个offer吗?
avatar
S*C
3
没人知道?
avatar
m*2
4
ac的一个,不知道是不是最优
public class Solution {
/**
* @param nums: A list of integers
* @param k: As described
* @return: The majority number
*/
public int majorityNumber(ArrayList nums, int k) {
if (nums == null || nums.size() == 0 || k > nums.size() || k <= 0) {
return Integer.MAX_VALUE;
}

int[] value = new int[k];
int[] count = new int[k];
for (int i = 0; i < k; i++) {
count[i] = 0;
}


int n = nums.size();

for (int i = 0; i < n; i++) {
boolean startnew = true;
for (int j = 0; j < k; j++) {
if (count[j] > 0 && value[j] == nums.get(i)) {
count[j]++;
startnew = false;
break;
}
}

if (startnew) {
for (int j = 0; j < k; j++) {
if (count[j] == 0) {
value[j] = nums.get(i);
count[j] = 1;
break;
}
}
}

int minheight = Integer.MAX_VALUE;
for (int j = 0; j < k; j++) {
minheight = Math.min(minheight,count[j]);
}
for (int j = 0; j < k; j++) {
count[j] -= minheight;
}
}
int maxcount = 0;
int maxvalue = Integer.MAX_VALUE;
for (int i = 0; i < k; i++) {
if (count[i] > 0) {
int curcount = 0;
for (int j = 0; j < n; j++) {
if (nums.get(j) == value[i]) {
curcount++;
}
}
if (curcount > maxcount) {
maxcount = curcount;
maxvalue = value[i];
}
}
}
return maxvalue;
}
}

【在 S*******C 的大作中提到】
: 没人知道?
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。