Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

写出可执行方法统计出数组中每个数据出现的次数,你的方案是什么,复杂度是多少 #2

Open
robinson90 opened this issue Dec 12, 2018 · 2 comments

Comments

@robinson90
Copy link
Owner

如题

@robinson90
Copy link
Owner Author

出这样一个题,是基于自己在面试的时候有这样一道笔试题,考察统计出一个数组中,出现次数大于一半以上的数字,如果没有返回0 。

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字,要求只遍历一次。

例如:输入一个长度为9的数组[1,6,3,6,6,6,5,4,6]。由于数字6在数组中出现了5次,超过数组长度的一半,因此输出6。如果不存在则输出0。

// 假设数组为纯数字数组
function getHalfChanceNumber(arr) {
    if (!arr) return 0
    if (!arr.length) return 0
    var len = arr.length
    var hasCountHalf = false
    var countN = {}
    for (var i = 0 ; i < len; i++) {
       countN[arr[i]] = countN.hasOwnProperty(arr[i]) ? ++countN[arr[i]] : 1
       if (countN[arr[i]] > len / 2) {
          hasCountHalf = true
          return arr[i]
        }
    }
   if (!hasCountHalf) return 0
  }

@ghost
Copy link

ghost commented Mar 24, 2019

// 使用正则的方式实现的
function filter(arr) {
  if (!Array.isArray(arr) || arr.length < 1) return 0;
  if (arr.length < 2) return arr[0];

  const threshold = Math.ceil(arr.length / 2) - 1;
  const regexp = new RegExp(`(?<duplicate>\\d+)(?=(?:,\\k<duplicate>){${threshold},})`);

  const result = arr.sort((a, b) => b - a).toString().match(regexp);
  return result ? +result[0] : 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant