初級摩爾投票算法;

int majorityElement(int* nums, int numsSize){get

int count=0 ,i;it

int target=nums[0];co

for(i=0;i<numsSize;i++)return

{tar

if(count==0)

{

target=nums[i];

}

if(nums[i]==target)

count++;

else

count--;

}

if(count>0)

return target;

else

return 0;

}

思路: 當建設存在一個number 它的count>numbersize/2;則兩個不一樣的數相遇時消去時最後剩下的就是mian number;
或則對一個爲 mainnumber 的數而言兩兩配對(爲奇數時最後三個兩兩配對 ) 必有相同的miannumber

eg 1 2 5 9 5 5 5

1step 5 9 5 5 5

2 step 5 5 5;

eg 1 1 1 2 2

1step 1 1 1 2 2

2step 1 1 2

3step 1 ;

僞代碼 for(i=0;i<numsSize;i++) //建設第一個爲mainnumber;

{

if(count==0)// 當爲count=0 時更換mainnumber

{

target=nums[i];

}

if(nums[i]==target) 相同時就count++

count++;

else 不一樣時就 count--;

count--;

}

相關文章
相關標籤/搜索