LeetCode 169題解


/**
 * 類說明
 * 給定一個大小爲 n 的數組,找到其中的多數元素。多數元素是指在數組中出現次數大於 ⌊ n/2 ⌋ 的元素。

你可以假設數組是非空的,並且給定的數組總是存在多數元素。

 

示例 1:

輸入: [3,2,3]
輸出: 3

示例 2:

輸入: [2,2,1,1,1,2,2]
輸出: 2

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/majority-element
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
 * 
 * 思路1:  暴力,兩次循環
 * 思路2: 用map O(n)
 * 思路3:排序, 取中間的,然後比較???
 * 思路4: 分治算法,一份爲2  left 找到次數大多數值,右邊找打最大值 left == right 那麼說明這個數就是最大
 * 不想 count(left) > count(right)? count(left):count(right)
 * O(NLogN)
 * <pre>
 * Modify Information:
 * Author        Date          Description
 * ============ =========== ============================
 * wangm          2020年5月24日    Create this file
 * </pre>
 * 
 */

public class LeetCode169 {

    public int majorityElement(int[] nums) {
        return  findMajorityElment(nums,0,nums.length-1);
    }
    
    /**
     * @param nums
     * @param i
     * @param mid
     * @return
     */
    private int findMajorityElment(int[] nums, int start, int end) {
        int mid = start+ (end-start)/2;
        if(start == end){
            return nums[start];
        }
        int left = findMajorityElment(nums,start,mid);
        int right = findMajorityElment(nums,mid+1,end);
        if(left == right){
            return left;
        }
        return count(left,nums,start,mid)> count(right,nums,mid,end)?left:right;
    }

    /**
     * @param left
     * @param nums
     * @param start
     * @param mid
     * @return
     */
    private int count(int left, int[] nums, int start, int mid) {
        int cnt = 0;
        for(int i = start; i < mid ;i++){
            if(nums[i] == left){
                cnt+=1;
            }
        }
        return cnt;
    }

    public static void main(String[] args) {
//        int[] nums = new int[]{2,2,1,1,1,2,2}; //2
//        int[] nums = new int[]{3,2,3}; //3
        int[] nums = new int[]{3,3,4}; //3
        System.out.println(new LeetCode169().majorityElement(nums));
    }

}

分治算法模板

分治算法模板

def divide_comquer(problem, param1, parana, ... )

#recursion terminator 
if problem is None:
    print result
return 
# prepare data 
data =  prepare_data(problem)
spLit_problems = split_problem(problem_data)
# conquer subproblems
subresult1 = self.divide_conquer(subproblems[0],p1,...)
subresult2 self.divide_conquer(subproblems[l], pl,...)
subresult3= self.divide_conquer(subproblems[2], pl,...)
... 
# proress anmd generate the FInal nesult 
result = process_ result(subresultl, subresult2, subresult3, ...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章