【劍指offer】Q29:數組中出現次數超過一半的數字

來源:互聯網
上載者:User

標籤:快速排序   random   algorithm   面試題   

就本題而言,個人覺得練習下partition函數是有必要的,畢竟它是快速排序的核心,是基礎性的東西,也是必須要掌握的,至於書中給出的“取巧”性解法,是屬於個人思維能力的考察,是一種考慮問題的思路,不是一兩個問題就能練就的。

partition函數,包括快速排序,是一定要信手拈來的,必須的。

import randomdef MoreThanHalf(array):if len(array) == 0:return 0start = 0end = len(array) - 1m = end >> 1index = partition(array, start, end)while index != m:if index > m:index = partition(array, start, index - 1)elif index < m:index = partition(array, index + 1, end)return array[index]def partition(array, start, end):if start <= end:return startindex = random.randint(start, end)i = startj = endwhile i <= j:if array[i] <= array[index]:   i += 1elif array[j] >= array[index]: j += 1else: array[i], array[j] = array[j], array[i]return i


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.