0
点赞
收藏
分享

微信扫一扫

力扣算法题:多数元素 --多语言实现

追风骚年 2024-06-09 阅读 8

无意间看到,力扣存算法代码居然还得升级vip。。。好吧,我自己存吧

golang:

func majorityElement(nums []int) int {
    count := 0
    condidate := 0
    for _,val := range nums {
       if count == 0 {
        condidate = val
        count = 1
       } else if val == condidate {
        count++
       } else {
        count--
       }
    }
    return condidate
}

javascript:

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    let count = 0
    let cumber = 0
    for(let i=0; i< nums.length; i++) {
        if(count == 0) {
            count = 1
            cumber = nums[i]
        } else if(cumber == nums[i]) {
            count++
        } else {
            count--
        }
    }
    return cumber
};

python:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        cumber = 0
        for num in nums:
            if count == 0:
                count = 1
                cumber = num
            elif num == cumber:
                count += 1
            else:
                count -= 1
        return cumber
举报

相关推荐

0 条评论