由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 求解lintcode Majority Number III
相关主题
lintcode Majority Number II 怎么做?贡献一个最近电面题目
lintcode 上的 Count of Smaller Number before itselffind Kth Largest Element 有没有更简化的解法
lintcode delete digits怎么做?问个amazon面试题
lintcode subarray sum 怎么做?请教一道算法题
G家onsite 随机数一题G电面面经
问个fb onsite题目a problem from leetcode: high efficiency algorithm for combinations problem
peak element II 怎么做combinations 有没有 iterative的方法阿 ?
find all longest increasing subsequence 谁有源码?问个递归的问题
相关话题的讨论汇总
话题: int话题: value话题: count话题: number话题: majority
进入JobHunting版参与讨论
1 (共1页)
S*******C
发帖数: 822
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/
S*******C
发帖数: 822
2
没人知道?
m***2
发帖数: 595
3
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 的大作中提到】
: 没人知道?
1 (共1页)
进入JobHunting版参与讨论
相关主题
问个递归的问题G家onsite 随机数一题
九章算法的 解答不怎么样啊问个fb onsite题目
求点评:电话面试(今天第二天没有消息回复,感觉可能挂了)peak element II 怎么做
问个google面试题的最佳解法find all longest increasing subsequence 谁有源码?
lintcode Majority Number II 怎么做?贡献一个最近电面题目
lintcode 上的 Count of Smaller Number before itselffind Kth Largest Element 有没有更简化的解法
lintcode delete digits怎么做?问个amazon面试题
lintcode subarray sum 怎么做?请教一道算法题
相关话题的讨论汇总
话题: int话题: value话题: count话题: number话题: majority