Leetcode - Majority Element
Leetcode - Decompress Run-Length Encoded List

Leetcode - Majority Element II

violet posted @ May 07, 2020 05:46:02 AM in 算法 with tags Algorithm Golang Vote array , 291 阅读

https://leetcode.com/problems/majority-element-ii

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

 

Boyer-Moore Vote algorithm

func majorityElement(nums []int) []int {
    if len(nums) == 0 {
        return []int{}
    }
    candidate1 := 0
    candidate2 := 1
    count1 := 0
    count2 := 0
    
    for _, n := range nums {
        if n == candidate1 {
            count1++
        } else if n == candidate2 {
            count2++
        } else if count1 == 0 {
            candidate1 = n
            count1 = 1
        } else if count2 == 0 {
            candidate2 = n
            count2 = 1
        } else {
            count1--
            count2--
        }
    }
    count1 = 0
    count2 = 0
    for _, n := range nums {
        if n == candidate1 {
            count1++
        }
        if n == candidate2 {
            count2++
        }
    }
    result := []int{}
    if count1 > len(nums)/3 {
        result = append(result, candidate1)
    }
    if count2 > len(nums)/3 {
        result = append(result, candidate2)
    }
    return result
}
IFMS Odisha 说:
Aug 05, 2022 09:19:04 PM

iFMS can be designed as per required by the entity, by modifying it to custom made system or off-the-shelf software, and based on the size and requirement of the entity iFMS is designed which further invoices in improvement of organization financial management. IFMS Odisha This system brings numerous management functions into one software suite and iFMS is also referred to as Integrated Financial Management Information System (IFMIS), where many government and private firms use this as their key HRMS portal to manage their distribution with employees and customers, which allows them to track spending in one page with less effort.

Rajasthan Board 4th 说:
Aug 21, 2022 06:48:52 PM

Rajasthan Board Model Paper 2023 Class 4 Pdf Download with Answers for Rajasthani Medium, English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. Rajasthan Board 4th Class Model Paper New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter