1. 程式人生 > >LeetCode169 Majority Element, LintCode47 Majority Number II, LeetCode229 Majority Element II, LintCode48 Majority Number III

LeetCode169 Majority Element, LintCode47 Majority Number II, LeetCode229 Majority Element II, LintCode48 Majority Number III

LeetCode169. 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. (Easy)

You may assume that the array is non-empty and the majority element always exist in the array.

分析:

抵消的思想,維護一個result和count,與result相同則count++,否則count--,到0時更新result的值,由於主元素個數較多,所有最後一定能留下。

程式碼:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int result = 0;
 5         int count = 0;
 6         for (int i = 0; i < nums.size(); ++i) {
 7             if (nums[i] == result && count != 0) {
 8                 count++;
 9             }
10 else if (count == 0) { 11 result = nums[i]; 12 count = 1; 13 } 14 else { 15 count--; 16 } 17 } 18 return result; 19 } 20 };

LintCode47. Majority NumberII

Given an array of integers, the majority number is the number that occurs more than 1/3

 of the size of the array. (Medium)

Find it.

Notice : There is only one majority number in the array. 

分析:

同majority number1的思路相似,維護兩個result和count,相同則對相應count操作,不同則均減一;

注意最後剩下兩個元素,並不一定count值大的就一定是出現次數多的(可能另一個參與抵消過多),所以需要重新遍歷一遍,對這個兩個數比較出現次數大小。

程式碼:

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: A list of integers
 5      * @return: The majority number occurs more than 1/3.
 6      */
 7     int majorityNumber(vector<int> nums) {
 8         // write your code here
 9         int candidate1 = 0, candidate2 = 0;
10         int count1 = 0, count2 = 0;
11         for (int i = 0; i < nums.size(); ++i) {
12             if (nums[i] == candidate1 && count1 != 0) {
13                 count1++;
14             } 
15             else if (nums[i] == candidate2 && count2 != 0) {
16                 count2++;
17             }
18             else if (count1 == 0) {
19                 candidate1 = nums[i];
20                 count1 = 1;
21             }
22             else if (count2 == 0) {
23                 candidate2 = nums[i];
24                 count2 = 1;
25             }
26             else {
27                 count1--;
28                 count2--;
29             }
30         }
31         count1 = 0;
32         count2 = 0;
33         for (int i = 0; i < nums.size(); ++i) {
34             if (nums[i] == candidate1) {
35                 count1++;
36             }
37             else if (nums[i] == candidate2) {
38                 count2++;
39             }
40         }
41         return count1 > count2 ? candidate1 : candidate2;
42     }
43 };

LeetCode229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.(Medium)

分析:

這個與lintcode中的majority number2基本相似,只是要求找到所有的大於n / 3次的元素(至多也就是兩個);

所以最後一步從比較兩個canditate的count大小,變成將這兩個count與 size() / 3比較。

程式碼:

 1 class Solution {
 2 public:
 3     vector<int> majorityElement(vector<int>& nums) {
 4         int candidate1 = 0, candidate2 = 0;
 5         int count1 = 0, count2 = 0;
 6         for (int i = 0; i < nums.size(); ++i) {
 7             if (nums[i] == candidate1 && count1 != 0) {
 8                 count1++;
 9             } 
10             else if (nums[i] == candidate2 && count2 != 0) {
11                 count2++;
12             }
13             else if (count1 == 0) {
14                 candidate1 = nums[i];
15                 count1 = 1;
16             }
17             else if (count2 == 0) {
18                 candidate2 = nums[i];
19                 count2 = 1;
20             }
21             else {
22                 count1--;
23                 count2--;
24             }
25         }
26         count1 = 0;
27         count2 = 0;
28         for (int i = 0; i < nums.size(); ++i) {
29             if (nums[i] == candidate1) {
30                 count1++;
31             }
32             else if (nums[i] == candidate2) {
33                 count2++;
34             }
35         }
36         vector<int> result;
37         if (count1 > nums.size() / 3) {
38             result.push_back(candidate1);
39         }
40         if (count2 > nums.size() / 3) {
41             result.push_back(candidate2);
42         }
43         return result;
44 
45     }
46 };

LintCode48. Majority Number III

Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. (Medium)

Find it.

Notice:There is only one majority number in the array.

分析:

從前一題的1/3變為1/k,道理還是一樣,不過這次需要用一個hashmap來維護出現的次數,注意unordered_map插入刪除相關操作的寫法即可。

尤其hashmap元素個數等於k需要刪除的時候,需要維護一個vector存key,如果用iterator邊走邊刪除可能出現位置變化。

程式碼:

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: A list of integers
 5      * @param k: As described
 6      * @return: The majority number
 7      */
 8     int majorityNumber(vector<int> nums, int k) {
 9         // write your code here
10         unordered_map<int, int> hash;
11         for (int i = 0; i < nums.size(); ++i) {
12             if (hash.size() < k) {
13                 hash[nums[i]]++;
14             }
15             else {
16                 vector<int> eraseVec;
17                 for (auto itr = hash.begin(); itr != hash.end(); ++itr) {
18                     (itr -> second)--;
19                     if (itr -> second == 0) {
20                         eraseVec.push_back(itr -> first);
21                     }
22                 }
23                 for (int i = 0; i < eraseVec.size(); ++i) {
24                     hash.erase(eraseVec[i]);
25                 }
26                 hash[nums[i]]++;
27             }
28         }
29         for (auto& n : hash) {
30             n.second = 0;
31         }
32         for (int i = 0; i < nums.size(); ++i) {
33             if (hash.find(nums[i]) != hash.end()) {
34                 hash[nums[i]]++;
35                 if (hash[nums[i]] > nums.size() / k) {
36                     return nums[i];
37                 }
38             }
39         }
40         return -1;
41     }
42 };

相關推薦

LeetCode169 Majority Element, LintCode47 Majority Number II, LeetCode229 Majority Element II, LintCode48 Majority Number III

LeetCode169. 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

【LeetCode-面試算法經典-Java實現】【059-Spiral Matrix II(螺旋矩陣II)】

mod 最大 http 計算 spiral tro parent 全部 matrix 【059-Spiral Matrix II(螺旋矩陣II)】 【LeetCode-面試算法經典-Java實現】【全部題目文件夾索引】 原題   Given

672. Bulb Switcher II 燈泡切換器II

exactly fit amp pri ted turn owa post preview There is a room with n lights which are turned on initially and 4 buttons on the wall. Aft

分割回文串 II · Palindrome Partitioning II

class nbsp 英文 長度 總結 正常 bsp 風格 思路 [抄題]: 給定一個字符串s,將s分割成一些子串,使每個子串都是回文。 返回s符合要求的的最少分割次數。 [思維問題]: [一句話思路]: [輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常

142 Linked List Cycle II 環形鏈表 II

OS return leetcode 開始 ext 修改 cpp urn scrip 給一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。說明:不應修改給定的鏈表。補充:你是否可以不用額外空間解決此題?詳見:https://leetcode.com/

[leetcode]680. Valid Palindrome II有效回文II(可至多刪一原字符)

span cti pan col rac helper code delet example Given a non-empty string s, you may delete at most one character. Judge whether you can ma

LeetCode 132. 分割回文串 II(Palindrome Partitioning II

題目描述   給定一個字串 s,將 s 分割成一些子串,使每個子串都是迴文串。 返回符合要求的最少分割次數。 示例: 輸入: "aab" 輸出: 1 解釋: 進行一次分割就可將 s 分割成 ["aa","b"] 這樣兩個迴文子串。 &nb

quatus ii------除錯利器 SignalTap II簡介(基於TIGER BOARD 板子)

1.為什麼要用SignalTap ii:   在上板執行前都需要進行模擬,Modelsim 的使用可以使 FPGA 設計的許多錯誤扼殺在上板執行前,但這並不代表有了 Modelsim,我們的設計就天衣無縫了。實際上,在真正的上板執行時,我們還有可能遇到這樣那樣的問題,原因

LeetCode 92. 反轉連結串列 II(Reverse Linked List II)

題目描述 反轉從位置 m 到 n 的連結串列。請使用一趟掃描完成反轉。 說明: 1 ≤ m ≤ n ≤ 連結串列長度。 示例: 輸入: 1->2->3->4->5->NULL, m = 2, n = 4 輸出: 1->4->3

[Swift]LeetCode92. 反轉連結串列 II | Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass. Note: 1 ≤ m ≤ n ≤ length of list. Example: Input:

C#LeetCode刷題之#541-反轉字串 II(Reverse String II

問題 給定一個字串和一個整數 k,你需要對從字串開頭算起的每個 2k 個字元的前k個字元進行反轉。如果剩餘少於 k 個字元,則將剩餘的所有全部反轉。如果有小於 2k 但大於或等於 k 個字元,則反轉前 k 個字元,並將剩餘的字元保持原樣。 輸入: s = "abcdefg", k

52.N皇后II(N-Queens II

題目描述 n 皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,並且使皇后彼此之間不能相互攻擊。 給定一個整數 n,返回 n 皇后不同的解決方案的數量。 解題思路 嗯,這題就是上一題(51.N皇后)的翻版,上一題要求輸出所有解法,這一題卻只要求數量就行了。 所以。

45. 跳躍遊戲II(Jump Game II

題目描述 給定一個非負整數陣列,你最初位於陣列的第一個位置。 陣列中的每個元素代表你在該位置可以跳躍的最大長度。 你的目標是使用最少的跳躍次數到達陣列的最後一個位置。 示例: 輸入: [2,3,1,1,4] 輸出: 2 解釋: 跳到最後一個位置的最小跳躍數是 2。 從下標為

【LeetCode】Linked List Cycle II(環形連結串列 II)

這是LeetCode裡的第142道題。 題目要求: 給定一個連結串列,返回連結串列開始入環的第一個節點。 如果連結串列無環,則返回 null。 說明:不允許修改給定的連結串列。 進階:你是否可以不用額外空間解決此題? 起初我在做這道題的時候,

Java/ 910. Smallest Rangle II 最小差值 II

題目 程式碼部分一(16ms) class Solution { public int smallestRangeII(int[] A, int K) { Arrays.sort(A); int

leetcode 219. Contains Duplicate II(存在重複元素 II)--Java題解

題目描述 給定一個整數陣列和一個整數 k,判斷陣列中是否存在兩個不同的索引 i 和 j,使得 nums [i] = nums [j],並且 i 和 j 的差的絕對值最大為 k。 示例  輸入:nums = [1, 2, 3, 1], k = 3 輸出:true 輸入

【LeetCode】#142環形連結串列II(Linked List Cycle II)

【LeetCode】#142環形連結串列II(Linked List Cycle II) 題目描述 給定一個連結串列,返回連結串列開始入環的第一個節點。 如果連結串列無環,則返回 null。 為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索

Leetcode演算法——59、螺旋矩陣II(square matrix II

給定一個正整數 n,要求生成一個方陣,裡面的元素為1到n^2按照螺旋順序排列。 示例: Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 思路 可以參考 Leetcode演算法——54、螺旋矩陣(

[Swift Weekly Contest 116]LeetCode963. 最小面積矩形 II | Minimum Area Rectangle II

Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily para

45. Jump Game II(跳躍遊戲II

問題描述 Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the a