有一个乱序的数组,其中有一个数占了一半以上,找出这个数
三种方法: 1.一次遍历,筛掉两个不同的数,其剩余数组中,频率超过一半的数还是超过一半...
2.排序, 选取中间的那个数,即是
3.放到MAP中,选取频率最高的那个数
三种方法: 1.一次遍历,筛掉两个不同的数,其剩余数组中,频率超过一半的数还是超过一半...
2.排序, 选取中间的那个数,即是
3.放到MAP中,选取频率最高的那个数
标签: <无>
代码片段(1)[全屏查看所有代码]
1. [代码]找出数组中频率超过一般的数
01 | import random |
02 |
03 | specified = 4; |
04 |
05 | # generate standard sample |
06 | def f(x): |
07 | if x%2 == 0 or x%7 == 0:return specified |
08 | return random.randint(1,100) |
09 | array = map(f, xrange(0,100)) |
10 | #random.shuffle(array) |
11 | #print array.count(specified) |
12 |
13 | # findout the value , Tree method to solve the question: |
14 | def findoutSpecifiedByIterOnce(array): |
15 | temp = array[0] |
16 | count = 1 |
17 | for i in xrange(1, len(array)): |
18 | if count == 0: |
19 | temp = array[i] |
20 | count += 1 |
21 | continue |
22 | if temp == array[i]: |
23 | count += 1 |
24 | else: |
25 | count -= 1 |
26 | #print "show ", temp |
27 | return temp |
28 |
29 | def findoutSpecifiedBySort(array): |
30 | array.sort() |
31 | return array[len(array)/2] |
32 |
33 | def findoutSpecifiedByMap(array): |
34 | arrayCountMap = {x : array.count(x) for x in set(array)} |
35 | return sorted(arrayCountMap.items(), key=lambda arrayCountMap:arrayCountMap[1], reverse=True)[0][0] |
36 |
37 |
38 | print findoutSpecifiedByIterOnce(array) == specified |
39 | print findoutSpecifiedByMap(array) == specified |
40 | print findoutSpecifiedBySort(array) == specified |

1009

被折叠的 条评论
为什么被折叠?



