Reflections on LeeCode a simple question caused

  [Introduction] might read my blog before friends will find this issue a little bit different, hhhh, how I become the title of the party? ? ? No, but I would like to pass this LeeCode simple questions (we could usually dismissive) something to think deeply, friends who are interested can read on.


  [Title] Most element 169.

    Title Description: Given an array of size n, the majority of the elements found therein. Most is the number of elements present in the array is greater than ⌊ n / 2 ⌋ elements.

    You can assume that the array is non-empty, and there is always most elements of a given array.


    Example:

    	示例 1:
    		输入: [3,2,3]
			输出: 3
 				  			 		
		示例 2:
			输入: [2,2,1,1,1,2,2]
			输出: 2

    思路一:If you have understood the list中countmethod of friends, the mind may pop out of the first one is this idea, because it only needs to go through the list, and each value is counted in the list, when it is greater than n / 2 returns. Then there is the following code:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        sum_prices = 0  
        for i in range(1,len(prices)):
            if(prices[i]>prices[i-1]):  判断是否该买入
                sum_prices = sum_prices + prices[i]-prices[i-1]
            else:
                continue
        return sum_prices

    The result:
    Here Insert Picture Description
    the last input is [1,2,1,2 ... 1,2,3,3,3,3,3,3,3 ...], presumably to see here, with the count friend is not discovered what wrong, but it also led to my next idea.


    更进一步的思考:Due to the recent study in probability theory, so a bold idea burst out from my mind, if we are 不是顺序输入index对应的值进行计数,而是采用随机的方式, then from the viewpoint of probability, we only need a small number of results you can get close to one, so that feasible? The following experiment began.

import random
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sample_list = []
        for i in range(10):
            sample_list.append(random.randint(0,len(nums)-1))   #产生随机index
            if nums.count(nums[sample_list[i]]) >= len(nums)//2+1:  #采用count方法,对随机的index对应的值进行计数
                return nums[sample_list[i]]

    operation result:
    Here Insert Picture Description

    You're not wrong, we only had 10 times the random number to obtain a value greater than n / 2, and more than 99% of the execution time of a user

    Some knowledge about the link:

    The method for generating random numbers
    List count method


    But to do so, although the theory is feasible, but he said it somewhat opportunistic, then we how it had gone to this question?


    思路二:So this time, there may be some friends had thought to use a hash table statistics count, wanted to manually implement the process, but an official answer has caught my interest, we look at his code:

class Solution:
    def majorityElement(self, nums):
        counts = collections.Counter(nums)
        return max(counts.keys(), key=counts.get)

作者:LeetCode
链接:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/
来源:力扣(LeetCode)

    The result:
    Here Insert Picture Description
    everyone's attention to the Counter these methods do? That he and we count method What difference does it make? Why he can beat nearly 80% of users do when submitting? Since the code is implemented internally I have not found, it can only have a rough guess, know a friend can comment out below.

    思路三:Next, I would like to introduce an interesting algorithm, Boyer-Moore algorithm vote. His principle is to traverse the entire array to find the same number is incremented by one, to find a different number, it decreases, then the last remaining positive, that is the number of the mode, some of the popular saying is that a big team vote to A,
the remaining number of other small teams vote for B, then the final voting results was A, specific codes are as follows:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ticikes_num = 0
        candidate = 0
        for num in nums:
            if ticikes_num==0:
                candidate = num  #标记候选人
                ticikes_num = ticikes_num+1
            else:   #进行投票过程
                if candidate==num:   
                    ticikes_num = ticikes_num+1
                else:
                    ticikes_num = ticikes_num-1
        return candidate

    The result:
    Here Insert Picture Description


    思路四:there are some ways similar to divide and conquer, and so thinking, the use of the sort of problem-solving ideas, I will share the official problem-solving link below, if you have any unique problem-solving approach can also share below.


    Some knowledge about the link:
    algorithm explanations

    Share on here, welcome to discuss the exchange.


    注明

    Topic Source: stay button (LeetCode)
    link: https: //leetcode-cn.com/problems/majority-element

Published 32 original articles · won praise 62 · views 1265

Guess you like

Origin blog.csdn.net/Mingw_/article/details/104804870