Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
自己的解法:先排序, length/2 处的元素就是 majority
时间复杂度 : O(nlogn)
public class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; } }
另外一种比较容易想到的解法:运用hash table
时间复杂度:O(n)
空间复杂度 : O(n)
public class Solution { public int majorityElement(int[] nums) { HashMap<Integer, Integer> map = new HashMap<>(); int key, val, max = 1, maxKey = nums[0]; for (int i = 0; i < nums.length; i++) { key = nums[i]; if (!map.containsKey(key)) map.put(key, 1); else { val = map.get(key) + 1; if (max < val) { max = val; maxKey = key; } map.put(key, val); } } return maxKey; } }
别人家的解法:
据说叫做 Moore voting algorithm
时间复杂度: O(n)
public class Solution { public int majorityElement(int[] nums) { int maj = nums[0]; for (int i = 0, count = 0; i < nums.length; i++) { if (count == 0) { maj = nums[i]; count++; } else { count = maj == nums[i] ? count + 1 : count - 1; } } return maj; } }
还有一个用 Divide and Conquer 的方法
时间复杂度:O(nlogn)
public class Solution { public int majorityElement(int[] nums) { return majHelper(nums, 0, nums.length-1); } public int majHelper(int[] nums, int lo, int hi) { if (lo == hi) return nums[lo]; int temp1 = majHelper(nums, lo, (lo+hi)/2); int temp2 = majHelper(nums, (lo+hi)/2+1, hi); if (temp1 == temp2) return temp1; int count1 = 0, count2 = 0; for (int i = lo; i <= hi; i++) { if (nums[i] == temp1) count1++; else if (nums[i] == temp2) count2++; } return count1 > count2 ? temp1 : temp2; // 这里count1,count2随便,原因是什么需仔细思考 } }
再补充一个利用随机的方法
worst case running time: 无穷
import java.util.Random; public class Solution { public int majorityElement(int[] nums) { Random random = new Random(); for (int i = 0, k; i < 30; i++) { k = nums[random.nextInt(nums.length)]; for (int j = 0, count = 0; j < nums.length; j++) { if (k == nums[j]) count++; if (count > nums.length / 2) return k; } } return -1; } }
2015-10-21