摘要:投票法復(fù)雜度思路設(shè)定一個和這個對應(yīng)的如果一個數(shù)和這個相等,那么就將增加,否則減少的數(shù)目。
LeetCode[169] Majority Element
投票法Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.
You may assume that the array is non-empty and the majority element always exist in the array.
復(fù)雜度
O(N),O(1)
思路
設(shè)定一個candidate,和這個candidate對應(yīng)的count.如果一個數(shù)和這個candidate相等,那么就將count增加,否則減少count的數(shù)目。
代碼
public int majorityElement(int[] nums) { if(nums == null || nums.length == 0) return 0; int candidate = 0; int cnt = 0; for(int num : nums) { if(num == candidate) { cnt ++; } else if(cnt == 0) { candidate = num; } else { cnt --; } } return candidate; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65234.html
摘要:當(dāng)時題目改成了小明收紅包,找出現(xiàn)次數(shù)超過一般的那個紅包,要求線性時間復(fù)雜度,也就是說不能用排序排序算法最優(yōu)情況是。另外這個題在上的難度是哦,好傷心啊,當(dāng)初的我連這題都沒想出解法,真是夠年輕啊。 169. Majority Element Given an array of size n, find the majority element. The majority element i...
摘要:小鹿題目算法思路摩爾投票算法題目的要求是讓我們求數(shù)組中超過一半數(shù)據(jù)以上相同的元素且總是存在的。 Time:2019/4/4Title: Majority Element 1Difficulty: easyAuthor: 小鹿 題目:Majority Element 1 Given an array of size n, find the majority element. The ...
摘要:題目鏈接題目分析給定一個數(shù)組,返回其中出現(xiàn)次數(shù)超過一半的元素。思路用函數(shù)計算元素出現(xiàn)次數(shù),用逆序排序結(jié)果,輸出第一個即可。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 D83 169. Majority Element 題目鏈接 169. Majority Element 題目分析 給定一個數(shù)組,返回其中出現(xiàn)次數(shù)超過一半的元素。 思路 用array_count_values函數(shù)計算...
摘要:因為眾數(shù)出現(xiàn)的次數(shù)必定大于,所以我們只要取第個位置上的元素,這個元素一定為我們要找的眾數(shù)。 題目詳情 Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.You may assume th...
摘要:,這是最基礎(chǔ)的最大投票算法。例如,和這兩個數(shù)組最后得到的分別為和,但是這并不影響答案的正確性。接下來,我們可以對這個算法做一些簡單的擴(kuò)展,我們當(dāng)前定義的的數(shù)量大于的元素。為當(dāng)前出現(xiàn)的次數(shù)。這意味著當(dāng)前這個數(shù)字就是這兩個等待的第三個數(shù)字。 Boyer-Moore:A Linear Time Majority Vote Alogrithm,這是最基礎(chǔ)的最大投票算法。 原文中提到:decid...
閱讀 2791·2021-11-22 14:45
閱讀 936·2021-10-15 09:41
閱讀 1098·2021-09-27 13:35
閱讀 3767·2021-09-09 11:56
閱讀 2659·2019-08-30 13:03
閱讀 3224·2019-08-29 16:32
閱讀 3332·2019-08-26 13:49
閱讀 806·2019-08-26 10:35