class Solution {
public int inventoryManagement(int[] stock) {
//不同就抵消,最后剩余的数的数量肯定大于半数
int vote = 0, x = 0;
for (int num : stock) {
if (vote 0) {
x = num;
}
vote = x num ? vote + 1: vote – 1;
}
return x;
}
}
java
class Solution {
public int majorityElement(int[] nums) {
int votes = 0;
int x = 0;
for(int num : nums) {
if(votes == 0) {
x = num;
}
votes += (x == num ? 1 : -1);
}
return x;
}
}
class Solution:
def majorityElement(self, nums: List[int]) -> int:
res, cnt = None, 0
for num in nums:
res = res if cnt else num
cnt += (1 if res == num else -1)
return res
class Solution {
public int majorityElement(int[] nums) {
if(nums.length <= 2)return nums[0];
int x = nums[0];
int sum = 1;
for(int i = 1; i < nums.length; i++){
if(sum == 0){
x = nums[i];
sum = 1;
}else{
if(nums[i] == x){
sum ++;
}else{
sum --;
}
}
}
return x;
}
}
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums)
if n <= 2:
return nums[0]
cnt = 1
cur = nums[0]
for i in range(1, n):
if cnt == 0:
cur = nums[i]
cnt = 1
else:
if nums[i] == cur:
cnt += 1
else:
cnt -= 1
return cur
class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
int half = n/2;
HashMap<Integer, Integer> map = new HashMap<>();
int res = 0;
for(int x:nums){
if(map.get(x)!=null){
int value = map.get(x);
map.replace(x, value+1);
}else{
map.put(x, 1);
}
if(map.get(x)!=null && map.get(x)>half){
res = x;
break;
}
}
return res;
}
}
共以下 25 个回答
class Solution {
public int inventoryManagement(int[] stock) {
//不同就抵消,最后剩余的数的数量肯定大于半数
int vote = 0, x = 0;
for (int num : stock) {
if (vote 0) {
x = num;
}
vote = x num ? vote + 1: vote – 1;
}
return x;
}
}
class Solution {
public int majorityElement(int[] nums) {
int res = 0;
HashMap<Integer,Integer> hashmap = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(hashmap.containsKey(nums[i])){
hashmap.replace(nums[i],hashmap.get(nums[i])+1);
}else{
hashmap.put(nums[i],1);
}
}
for(Integer i:hashmap.keySet()){
if(hashmap.get(i)>(nums.length/2)){
return i;
}
}
return 0;
}
}
直接hashmap
“`java
class Solution {
public int majorityElement(int[] nums) {
if(nums.length<=2) return nums[0];
}
投票法:时间复杂度是O(N), 空间复杂度是O(1)
投票法,时间复杂度O(n) 空间复杂度O(1)
投票法
时间O(n)
空间O(1)
C++实现
“`C++& nums) {
int majorityElement(vector
int count = 0;
int candidate = 0;
}
“`
哈希
摩尔
【思路】对于一个majority数,将其与其他数字一比一抵消后依然会有多余,利用这个性质遍历一遍数组即可
【复杂度】时间复杂度O(n),空间复杂度O(1)
排序
时间:O(nlogn)
空间:O(logn)
官解 Boyer-Moore 投票算法
时间:O(n)
空间:O(1)
肯定在中间
MY摩尔投票
摩尔投票法,学到了
思想:采用哈希表记录次数
时间复杂度O(n) 空间复杂度O(n)
时间复杂度:O(n)
空间复杂度:O(1)
时间复杂度:O(N)
空间复杂度:O(1)
时间复杂度O(n)
c++实现& nums) {
int majorityElement(vector
int candidate =-1;
int count = 0;
for(int num:nums)
{
if(numcandidate) count++;
else if(–count<0)
{
candidate = num;
count=1;
}
}
return candidate;
}
时间复杂度:O(n)
额外空间复杂度:O(1)