class Solution {
public int inventoryManagement(int[] stock) {
int n = stock.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int s : stock) {
if (map.containsKey(s)) {
int now = map.get(s);
map.put(s, now + 1);
} else {
map.put(s, 1);
}
}
int id = 0;
int max = 0;
for (Integer key : map.keySet()) {
if (map.get(key) > max) {
max = map.get(key);
id = key;
}
}
return id;
}
}
摩尔投票:
时间复杂度O(n)
空间复杂度O(1)
class Solution {
public int inventoryManagement(int[] stock) {
int n = stock.length;
int id = 0;
int num = 0;
for (int s : stock) {
if (num == 0)
id = s;
if (s == id)
num++;
else
num--;
}
return id;
}
}
class Solution {
public:
int inventoryManagement(vector<int>& stock) {
int x = 0;
int v = 0;
for (int n : stock) {
if (v == 0) {
x = n;
}
if (n == x) {
v++;
}else {
v--;
}
}
return x;
}
};
//Boyer-Moore 投票算法
class Solution {
public int inventoryManagement(int[] stock) {
int candidate = 0, count = 0;
for (int id : stock) {
if (count 0) {
candidate = id;
}
count += (id candidate) ? 1 : -1;
}
class Solution {
public int inventoryManagement(int[] stock) {
if (stock.length <= 2) {
return stock[0];
}
int ans = stock[0];
int cnt = 1;
for (int i = 1; i < stock.length; i++) {
if (cnt != 0) {
if (stock[i] == ans) {
cnt++;
} else {
cnt--;
}
} else {
ans = stock[i];
// 这里不要忘记++
cnt++;
}
}
return ans;
}
}
共以下 9 个回答
哈希:
时间复杂度O(n)
空间复杂度O(n)
摩尔投票:
时间复杂度O(n)
空间复杂度O(1)
解题思路
– 假设第一个是众数,往后遍历,相同+1,不同-1,直到等于0;之后再找后续数组的第一个作为众数
– 因为众数的数量超过一半,所以剩下的一定是众数
【题解1】
采用摩尔投票法,先假设众数为第一个元素,后面若出现相同的则加一,不同的则减一,做票数为0则重新选取当前元素众数。
时间复杂度O(N),空间复杂度O(1)。
//Boyer-Moore 投票算法
class Solution {
public int inventoryManagement(int[] stock) {
int candidate = 0, count = 0;
for (int id : stock) {
if (count 0) {
candidate = id;
}
count += (id candidate) ? 1 : -1;
}
}
map方法
On O1
思路:摩尔投票法。
时间复杂度:O(n)
空间复杂度:O(1)
神奇的方法