java 169. Divide和Conquer.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 169. Divide和Conquer.java相关的知识,希望对你有一定的参考价值。

<a>https://discuss.leetcode.com/topic/17446/6-suggested-solutions-in-c-with-explanations</a>

/*
1. Arrays.sort(nums) return nums[n/2];
2. Divide and Conquer
3. Majority Voting
*/
public class Solution {
    public int majorityElement(int[] nums) {
        if (nums == null || nums.length < 1) return 0;
        int[] tuple = new int[2];
        for (int num : nums) {
            if (num == tuple[0]) {
                tuple[1]++;
            } else if (tuple[1] > 0) {
                tuple[1]--;
            } else {
                tuple[0] = num;
            }
        }
        return tuple[0];
    }
}
// Sorting
public int majorityElement1(int[] nums) {
    Arrays.sort(nums);
    return nums[nums.length/2];
}

// Hashtable 
public int majorityElement2(int[] nums) {
    Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
    //Hashtable<Integer, Integer> myMap = new Hashtable<Integer, Integer>();
    int ret=0;
    for (int num: nums) {
        if (!myMap.containsKey(num))
            myMap.put(num, 1);
        else
            myMap.put(num, myMap.get(num)+1);
        if (myMap.get(num)>nums.length/2) {
            ret = num;
            break;
        }
    }
    return ret;
}

// Moore voting algorithm
public int majorityElement3(int[] nums) {
    int count=0, ret = 0;
    for (int num: nums) {
        if (count==0)
            ret = num;
        if (num!=ret)
            count--;
        else
            count++;
    }
    return ret;
}

// Bit manipulation 
public int majorityElement(int[] nums) {
    int[] bit = new int[32];
    for (int num: nums)
        for (int i=0; i<32; i++) 
            if ((num>>(31-i) & 1) == 1)
                bit[i]++;
    int ret=0;
    for (int i=0; i<32; i++) {
        bit[i]=bit[i]>nums.length/2?1:0;
        ret += bit[i]*(1<<(31-i));
    }
    return ret;
}
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        return majority(nums, 0, nums.size() - 1);
    }
private:
    int majority(vector<int>& nums, int left, int right) {
        if (left == right) return nums[left];
        int mid = left + ((right - left) >> 1);
        int lm = majority(nums, left, mid);
        int rm = majority(nums, mid + 1, right);
        if (lm == rm) return lm;
        return count(nums.begin() + left, nums.begin() + right + 1, lm) > count(nums.begin() + left, nums.begin() + right + 1, rm) ? lm : rm;
    }
}; 

以上是关于java 169. Divide和Conquer.java的主要内容,如果未能解决你的问题,请参考以下文章

java 169. Divide和Conquer.java

java 169. Divide和Conquer.java

java 169. Divide和Conquer.java

java 169. Divide和Conquer.java

Divide and Conquer-169. Majority Element

[leetcode]Divide and Conquer-169. Majority Element