Problem
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.
Solutionclass Solution { public int majorityElement(int[] nums) { if (nums == null || nums.length == 0) return -1; Mapupdate 2018-11map = new HashMap<>(); for (int num: nums) { if (map.containsKey(num)) { if (map.get(num)+1 > nums.length/2) { return num; } else { map.put(num, map.get(num)+1); } } else { map.put(num, 1); } } return -1; } }
class Solution { public int majorityElement(int[] nums) { int count = 0; int res = nums[0]; for (int num: nums) { if (count == 0) { res = num; count++; } else if (num == res) { count++; } else { count--; } } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/69083.html
摘要:小鹿題目算法思路摩爾投票算法題目的要求是讓我們求數(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 ...
摘要:當(dāng)時(shí)題目改成了小明收紅包,找出現(xiàn)次數(shù)超過一般的那個(gè)紅包,要求線性時(shí)間復(fù)雜度,也就是說不能用排序排序算法最優(yōu)情況是。另外這個(gè)題在上的難度是哦,好傷心啊,當(dāng)初的我連這題都沒想出解法,真是夠年輕啊。 169. Majority Element Given an array of size n, find the majority element. The majority element i...
摘要:投票法復(fù)雜度思路設(shè)定一個(gè)和這個(gè)對應(yīng)的如果一個(gè)數(shù)和這個(gè)相等,那么就將增加,否則減少的數(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...
摘要:因?yàn)楸姅?shù)出現(xiàn)的次數(shù)必定大于,所以我們只要取第個(gè)位置上的元素,這個(gè)元素一定為我們要找的眾數(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...
摘要:排序法復(fù)雜度時(shí)間空間思路將數(shù)組排序,這時(shí)候數(shù)組最中間的數(shù)肯定是眾數(shù)。投票法復(fù)雜度時(shí)間空間思路記錄一個(gè)變量,還有一個(gè)變量,開始遍歷數(shù)組。代碼投票法復(fù)雜度時(shí)間空間思路上一題中,超過一半的數(shù)只可能有一個(gè),所以我們只要投票出一個(gè)數(shù)就行了。 Majority Element I Given an array of size n, find the majority element. The m...
閱讀 987·2021-11-24 10:30
閱讀 2316·2021-10-08 10:04
閱讀 3949·2021-09-30 09:47
閱讀 1433·2021-09-29 09:45
閱讀 1435·2021-09-24 10:33
閱讀 6234·2021-09-22 15:57
閱讀 2351·2021-09-22 15:50
閱讀 4079·2021-08-30 09:45