【每日一题】LeetCode 169. 多数元素 TypeScript

给定一个大小为 n的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

复制代码
输入:nums = [3,2,3]
输出:3

示例 2:

复制代码
输入:nums = [2,2,1,1,1,2,2]
输出:2

提示:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109
  • 输入保证数组中一定有一个多数元素。

做法1:排序后找中间数

TypeScript 复制代码
function majorityElement(nums: number[]): number {
    nums.sort((a,b)=>a-b)
    return nums[Math.floor(nums.length / 2)]
};

做法2:哈希表

TypeScript 复制代码
function majorityElement(nums: number[]): number {
    const Nmap = new Map<number,number>()
    const l2 = nums.length / 2
    for(const num of nums){
        const count = (Nmap.get(num) || 0) +1
        if(count>l2){
            return num
        }
        Nmap.set(num,count)
    }
    return -1
}

今日收获:

nums= 2,3,1,2,1

for(const num of nums) 遍历nums每一个元素,num输出数字型:2,3,1,2,1

for(const num in nums)遍历nums每一个索引,num输出字符型:"0"、"1"、"2"、"3"、"4"

什么时候用for.. in ..通常用来遍历对象

person = {name:'张三',age:18}

for(const per in person) 遍历nums的每一个键,per输出"name"、"age"

不推荐用for..in ..遍历数组,会遍历到数组的原型链上的属性

注意:of遍历数组,in遍历对象

of取值,in取键

共勉