您的位置:首页 > 职场人生

剑指offer--面试题29:数组中出现次数超过一半的数字

2016-09-27 18:05 555 查看


题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
python实现:
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution1(self, numbers):
        # write code here
        n = len(numbers)
        if n==0:
            return 0
        candidate = numbers[0]
        candidateCnt = 1#候选者的”计数“
        for i in range(1, n):
            if numbers[i] == candidate:
                candidateCnt += 1
            else:
                candidateCnt -= 1
            if candidateCnt==-1:
                candidate = numbers[i]
                candidateCnt = 1
        if self.checkMoreThanHalf(numbers, candidate):
            return candidate
        return 0
     
     
    #上面的方法只是找出了出现频率最高的数,但他不一定就是“众数”,还得检查是否满足个数>数组一半的条件
    def checkMoreThanHalf(self, numbers, candidate):
        cnt = 0
        for num in numbers:
            if num==candidate:
                cnt += 1
        return True if cnt>len(numbers)/2 else False   
     
     
        #法2:给予快排
    def MoreThanHalfNum_Solution(self, numbers):
        n = len(numbers)
        if n==0:
            return 0
        mid = (n-1)/2
        idx = self.partition(numbers, 0, n-1)
        low, high = 0, n-1
        while idx!=mid:
            if idx>mid:
                high = idx-1
                idx = self.partition(numbers, low, high)
            else:
                low = idx+1
                idx = self.partition(numbers, low, high)
        #此时idx对应的数还需要检查是否真的个数>n/2
        if self.checkMoreThanHalf(numbers, numbers[idx]):
            return numbers[idx]
        return 0
             
     
    def partition(self, nums, low, high):
        """
        from random import choice
        pivotIdx = choice(range(low, high+1))
        nums[low], nums[pivotIdx] = nums[pivotIdx], nums[low]
        """
        pivot = nums[low]
        while low<high:
            while low<high and nums[high]>=pivot:
                high -= 1
            nums[low] = nums[high]
            low += 1
            while low<high and nums[low]<=pivot:
                low += 1
            nums[high] = nums[low]
            high -= 1
        nums[low] = pivot
        return low

c++实现:
class Solution {
public:
    int MoreThanHalfNum_Solution1(vector<int> numbers) {
        if(numbers.empty())
            return 0;
        int candidate = numbers[0];
        int candidateCnt = 1;
        for(int i=1; i<numbers.size(); i++){
            if(numbers[i]==candidate)
                candidateCnt += 1;
            else
                candidateCnt -= 1;
            if(candidateCnt==-1){
                candidate = numbers[i];
                candidateCnt = 1;
            }
        }
          
        if(checkMoreThanHalf(numbers, candidate))
            return candidate;
        else
            return 0;
    }
      
    bool checkMoreThanHalf(vector<int> numbers, int candidate){
        int cnt = 0;
        for(auto num: numbers){
            if(num==candidate)
                cnt += 1;
        }
        return cnt>numbers.size()/2?true:false;
 
a7e3
   }
      
    //法2:基于快排
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.empty())
            return 0;
        int mid = numbers.size()>>1;
        int low = 0, high = numbers.size()-1;
        int idx = partition(numbers, low, high);
        while(idx!=mid){
            if(idx>mid){
                high = idx-1;
                idx = partition(numbers, low, high);
            }else{
                low = idx+1;
                idx = partition(numbers, low, high);
            }
        }
        if(checkMoreThanHalf(numbers, numbers[idx]))
            return numbers[idx];
        else
            return 0;
    }
      
    int partition(vector<int> &numbers, int low, int high){
        int pivot = numbers[low];
        while(low<high){
            while(low<high && numbers[high]>=pivot){
                high--;
            }
            numbers[low++] = numbers[high];
            while(low<high && numbers[low]<=pivot){
                low++;
            }
            numbers[high--] = numbers[low];
        }
        numbers[low] = pivot;
        return low;
          
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: