Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created May 24, 2014 23:57
Show Gist options
  • Save jikeytang/a5c944f565f98be39c0e to your computer and use it in GitHub Desktop.
Save jikeytang/a5c944f565f98be39c0e to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140525-题目2
数组中有一个数字出现的次数超过了数组长度的一半,找出这个数字。
如:[2,2],2出现2次,数组长度的一半为1。
[3,5,5,7],5出现2次,数组长度的一半为2,则为5。
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@zjhsd2007
Copy link

楼上的答案已经OK了,如果非要像一楼那样用正则的话,可以像这样实现:

(function(arr){
    var str = narr.sort().join(',')+',',l = Math.floor(narr.length/2)-1;
    var reg = new RegExp('(\\d+\\,)\\1{'+l+',}','g');
    return str.match(reg)[0].charAt(0); //1
})([2, 1, 2, 4, 2, 1, 4, 2, 1, 2, 1, 1, 1, 1]);

@styling
Copy link

styling commented May 30, 2014

想的窄了 没考虑mailzwj提出的问题 mark了

@zhanhongtao
Copy link

这个和当时我面试入职时的算法题类似.
我的是, 重复数字的长度多于总个数的一半 -- 不一样的数字碰碰消除, 剩下的就是结果.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment